Is it possible to swap the addresses of two variables?

前端 未结 3 1621
遥遥无期
遥遥无期 2021-01-15 16:10

I know that it is possible to swap the value of two variables like so

#include 

void swap(int *x, int *y);
int main(){
    int x=5,y=10;
             


        
3条回答
  •  借酒劲吻你
    2021-01-15 17:14

    Without passing pointers to pointers, it is not possible. All function calls in C are call by value. Function calls where parameters are of pointer type are often called as "call by reference" (which, by the way, is different from the C++ notion of call by reference) for convenience, but it too is actually call by value. See below example.

    void foo(int a, int b) {
        a = 0;
        b = 0;
    }
    
    void bar(int* ap, int* bp) {
        ap = NULL;
        bp = NULL;
    }
    
    void qux(int* ap, int* bp) {
        *ap = 0;
        *bp = 0;
    
        ap = NULL;
        bp = NULL;
    }
    
    int main() {
        int x = 2;
        int y = 3;
        int* xp = &x;
        int* yp = &y;
    
        foo(x, y); 
            // x and y don't change here
        bar(xp, yp);  
            // xp and yp don't change here
        qux(xp, yp);
            // xp and yp don't change here, but x and y do
    }
    

    It is easy to see how foo() is called by value. Copies of x and y are passed to it (hence call by value). Any changes it makes are to its own copy (which are named a and b within its scope). x and y are unaffected, and will not change in main() after this function returns.

    Although somewhat hard to understand for a beginner, bar() too is call by value. Copies of xp and yp are passed to it. Any changes it makes are to its own copy (which are named ap and bp within its scope). xp and yp are unaffected, and will not change in main() after this function returns.

    (Notice how the last 3 lines in above paragraph are nearly the same as the previous one. The only difference being that type of x and y are int, while that of xp and yp are int*.)

    qux() too is called by value, as it receives copies of xp and yp (known in its scope as ap and bp). However, it can dereference ap and bp, which being copies of xp and yp, point to the same memory location. The memory locations being known in main()'s scope by the names x and y. If qux() makes changes to the value in those memory locations, it will change main()'s "view" of x and y.

    The only way to change the values of those pointers through a called function, therefore, is to send addresses of those pointers to the function, which it can then dereference and potentially change. However, your question already rules out that option, so no, this is not possible.

提交回复
热议问题