C pointers - Point to the same address

后端 未结 7 1605
野趣味
野趣味 2021-02-10 15:38
#include 
#include 

void foo(int *a, int *b);

void foo(int *a, int *b) {
    *a = 5;
    *b = 6;
    a = b;
}

int main(void) {
    int          


        
7条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-10 16:22

    The call to foo() ends with its local variables pointing to the same addres, the one of stored in b. This change is not reflected in main(), the caller.

    I you liked to actually do this and make this change pemanent, then you would have to pass a pointer to a pointer to foo() (so you can change them), instead of their simple values:

    void foo(int **a, int **b) {
        **a = 5;
        **b = 6;
        *a = *b;
    }
    

    I have just observed that your code is incompatible with that modification, anyway, since you cannot change two normal variables to point to each other. You'd have to also modify main() this way:

    int main(void) {
        int a, b;
        int * ptrA = &a;
        int * ptrB = &b;
    
        foo(&ptrA, &ptrB);
        printf("%d, %d (%d, %d)", *ptrA, *ptrB, a, b);
        return 0;
    }
    

提交回复
热议问题