C pointers - Point to the same address

后端 未结 7 1601
野趣味
野趣味 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:14

    In foo, a and b are separate local variables. Setting them to have the same value has no effect on the previous values - the last line of foo currently does nothing, basically.

    Within foo, a is initially a pointer to the same location as a in main, and b is a pointer to the same location as b in main. The last line just makes the value of a in foo the same as b - namely a pointer to the same location as b in main. So if you add a line

    *a = 7;
    

    at the end of foo, then you'd see output of "5, 7".

    (Your code would definitely be easier to talk about if you used different variable names in main and foo, by the way.)

    If you're trying to make a and b within main "aliased" to each other, you're not going to be successful. They're separate local variables on the stack, and will remain so. You can't make the stack "shrink" to alias the two, whatever you do.

提交回复
热议问题