C pointers - Point to the same address

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

    Using a pseudo-memory map,

    In main(),

        a      b
     --------------
    |  5   |   6   | <- data
     --------------
     [1000]  [1004]  <- address
    

    In the function foo(),

        a        b      ( local to foo(), different from the a & b in main() )
     ----------------
    |  1000  | 1004  | <- data
     ----------------
      [2000]   [2004]  <- address
    

    So, when in foo()'s scope,

    *a = 5;   // store 5 in int variable a
    *b = 6;   // store 6 in int variable b
     a = b;   // copies contents of pointer variable b to a
    

    So the final map in foo()'s scope is:

        a        b
     ----------------
    |  1004  | 1004  | <- data
     ----------------
      [2000]   [2004]  <- address
    

提交回复
热议问题