2

After executing "0th sentence" memory address of n1, n2 and *pn were ADDR:0061FF2C, 0061FF28, 0061FF24. Do they change after executing 1), 2) and 3)? I put printf for every code but they do not seem to change. theoretically, shouldn't they change because variables were assigned new values?

#include <stdio.h> 
int main(void) 
{
    int n1=3, * pn = &n1;
    int n2=0;

    printf("%p, %p, %p\n", &n1, &n2, &pn);  // 0)
    n2 = *pn;                           // 1)
    *pn = n2 + 1;                   // 2)
    n1 = *pn + *(&n2);                      // 3)
    printf("%d, %d, %d\n",n1,n2,*pn);           // 4)
    return 0;
}
phuclv
  • 37,963
  • 15
  • 156
  • 475
Nathan Lee
  • 75
  • 1
  • 3
  • 10
  • O/T - you should cast those addresses to `void*` as `printf` expects, it's undefined behavior otherwise: https://stackoverflow.com/questions/9053658/correct-format-specifier-to-print-pointer-address – yano Nov 09 '17 at 04:52

2 Answers2

5

Let us see what the standard has to say about this -

Quoting C11, chapter §6.2.4p2

The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,[33] and retains its last-stored value throughout its lifetime. [...]

and

Quoting C11, chapter §note33

The term "constant address" means that two pointers to the object constructed at possibly different times will compare equal. The address may be different during two different executions of the same program.

Now here the objects that we have are n1, n2 and pn. All three of these have automatic storage durations.

Thus any two pointers constructed to these (using & like &n1, &n2 in the first printf) during different times will also compare equal. This is true even if their value changes over the course of execution.

Ajay Brahmakshatriya
  • 8,993
  • 3
  • 26
  • 49
2

No, the memory address will not change. Because assigning new values to any variable doesn't alter the memory address of the variable by any means. If this would be the case, then storing address of variables in a pointer variable would be meaningless, which is not like that.

Saket Sagar
  • 125
  • 1
  • 9