4

Pointer variables just points to other variable addresses in memory. And pointer variables have their own address in memory obviously.

However, This code is giving out the same memory address for both.

int num=10;
int *ptr=#
printf("Address of variable num: %p\n",ptr);
printf("Address of pointer ptr: %d\n",&ptr);

If a print both of them at the same time then it appears to work as expected.

Address of variable num: 0028FF3C

Address of pointer ptr: 0028FF38


But if I print them at one at a time then it's giving same address for both.

printf("Address of variable num: %p\n",ptr);
//printf("Address of pointer ptr: %d\n",&ptr);

Address of variable num: 0028FF38

//printf("Address of variable num: %p\n",ptr);
printf("Address of pointer ptr: %d\n",&ptr);

Address of pointer ptr: 0028FF38


I'm using mingw compiler on windows 7 machine.

Community
  • 1
  • 1
  • 2
    Compiler optimization at work? – DevSolar Nov 07 '15 at 10:48
  • 1
    It is probably because the compiler sees that you do not use the variable and optimizes it out. You can check by taking a look at the generated assembly code (gcc -S) – BrunoLevy Nov 07 '15 at 10:49
  • Being slightly pedantic: "Pointer variables just points to other **objects** in memory" is more accurate. There need not be any variable associated to the object the pointer points to. – MicroVirus Nov 07 '15 at 11:05

2 Answers2

4

The compiler only needs to guarantee that a variable lasts as long as it is used.

int a = 5;
int b = 7;
printf( "a * 5 = %d\n", a * 5); /* after this point, a is no longer needed */
printf( "b * 9 = %d\n", b * 9); /* after this point, b is no longer needed */

So the compiler can defer b initialization until after a is finished with, and only use one memory location.

Also in this example, it probably pushes the constants 25 and 63 onto the stack and doesn't create any storage for a or b.

AJNeufeld
  • 8,526
  • 1
  • 25
  • 44
mksteve
  • 12,614
  • 3
  • 28
  • 50
2

They are local variables allocated in the stack. So they have contiguous address assignments.

The compiler will normally remove any unused variables so commenting out the printf may result in the variably not being there. When one isn't there then only the first one gets put in the stack. Their addresses will be the same as long as the stack starts at the same place and has the same call stack and local variables on it.

You may want to have a look at the answers to this question if you don't know what the stack is. What and where are the stack and heap?

Community
  • 1
  • 1
FrankM
  • 772
  • 7
  • 11
  • 2
    To make your answer fully understandable, you probably need to explain also why "one is not there" since both are declared in the code, this is only the printf statement that is commented out (and compiler optimization removes the variable that is *not used*). – BrunoLevy Nov 07 '15 at 11:00