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

前端 未结 6 1034
无人共我
无人共我 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

    Given the statement:

    int v = 7; 
    

    v has some location in memory. Doing:

    x = &v;
    

    will "point" x to the memory location of v, and indeed *x will have the value 7.

    However, in this statement:

    *x = v;
    

    you are storing the value of v at the address pointed at by x. But x is not pointing at a valid memory address, and so this statement invokes undefined behavior.

    So to answer your question, no, the 2 statements are not equivalent.

提交回复
热议问题