Are `x = &v` and `*x = v` equivalent?

前端 未结 6 1007
无人共我
无人共我 2020-12-31 10:21
int * x;
int v = 7;

Given this code, what is the difference between 1. x = &v , and 2. *x = v ? I understand that

6条回答
  •  别那么骄傲
    2020-12-31 10:51

    These two are very different statements.

    Initially x will contain garbage value. Therefore *x will try to dereference an uninitialised address and will result in an undefined behaviour (in most of the cases a segmentation fault) as *x refers to something which is not initialised. Therefore, *x = v assigns the value in v to the location which is pointed by x.

    In the x = &v, x will contain the address of v. From this point x contains the address of v, *x will refer to the value in v. Therefore this statement is correct. Therefore, x = &v assigns the address of v as the value of x.

提交回复
热议问题