-1

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 :

enter image description here

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 ?

Community
  • 1
  • 1
Severus Tux
  • 265
  • 3
  • 13
  • 2
    *According to my understanding, `a` a name given to the address of `a`.* This is a misunderstanding. `a` is a name that represents a value that is at a specific address. So using `a` you access the value. Using `&a` you access the address of the value represented by `a`. And then `*a` assumes the value represented by `a` is itself an address, and `*a` refers to the value at that address. – lurker Aug 10 '17 at 10:19

3 Answers3

5

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 the register 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. [...]

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

Its probably more easily explained by the following simple code example:

printf("%d %d %d %d %d", &a , a , *a, &b, b);

which returns for example:

290289632 290289644 100 290289644 100
  • The address of a: &a is something allocated at start up (output item 1).
  • a points to the address of b hence output item 2 and 4 are the same.
  • The value at the address *a = b: hence output item 3 and 5 are the same.
Eamonn Kenny
  • 1,926
  • 18
  • 20
  • Remember that all variable created in a programmes startup phase must have different address spaces allocated to them. Therefore the address of a and b must be different. – Eamonn Kenny Aug 10 '17 at 10:02
0

Here basically *a stores the value of b which is 100,&a is the address of the pointer a itself since it is also a variable and thus must have an address, and a refers to the address of the variable is pointing to(b's address in this case)