int * x;
int v = 7;
Given this code, what is the difference between
1. x = &v
, and
2. *x = v
?
I understand that
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.
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.
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
.
The first assigns a value to x
. The second has undefined behaviour.
int v=7;
Let's say the address of v = 00ZXCDFCDGDD2345
int x=&v;
Here '&' means the address of and x is used to store the address *(00ZXCDFCDGDD2345)*
, and x itself stored at some location say *00254DBHJBDHDW*
.
Now if we want to access the value of v we use the pointer.
int *x=v;
In this statement '*x' is a pointer variable which points to v, means it stores the value of v but the x itself is undefined, it stores the garbage value. Hence both are different.
&
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
.