I am trying to understand the difference between a
and &a
when a is a pointer.
in the following example code :
int main()
{
int b = 100;
int *a;
a = &b;
printf("%d %d %d", a , &a , *a);
return 0;
}
According to my understanding, a is a name given to the address of a. That is :
Therefore I am expecting a
and &a
to be same when a
is a pointer. But in the output, I am getting the first two values ( a
and &a
) as different.
Where am I going wrong ?
First of all, use %p
and cast the argument to void *
for printing a pointer. Passing an incompatible (mismatched) type of argument for any conversion specification is undefined behavior.
That said, even a pointer variable, is a variable, and has to be "stored" in an address. So, it's the address of a pointer type variable.
In other words,
b
is a variable (of type int
) and it has an address.a
is a variable (of type int *
) and it also has an address.To add some reference, quoting C11
, chapter §6.5.3.2,
The operand of the unary
&
operator shall be either a function designator, the result of a[]
or unary*
operator, or an lvalue that designates an object that is not a bit-field and is not declared with theregister
storage-class specifier.
and, from §6.3.2.1,
An lvalue is an expression (with an object type other than
void
) that potentially designates an object. [...]