int * x;
int v = 7;
Given this code, what is the difference between
1. x = &v
, and
2. *x = v
?
I understand that
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
.