Are `x = &v` and `*x = v` equivalent?
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.
&
means address of.
*
means value at.
In x = &v
the address of v
is assigned to x
.
In *x = v
- the value at x
(the value at the address x
) is assigned the value v
.
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
.
x = &v
modifies x. After the operation x will point to v.
*x = v
modifies the object pointed by x. In the example, x doesn't point at anything because the pointer is uninitialised. As such, the behaviour is undefined.