I'm trying to understand how C is handling the conversion between a pointer and its address. Some courses online (openclassrooms) suggests that displaying a pointer with %d will just convert the hex to decimal format.
But trying to verify it, that's not the behaviour that i'm seeing.
At each run, the %p will display the same address, but with %d this value is different.
Would someone have an idea why ?
This is my code :
#include <stdio.h>
#include <stdlib.h>
int main (int arg, char *argv[]){
int age = 10; // variable age
int *ptrToAge = &age; // pointer (has the '*') that records the RAMemory address of the variable age
printf("The 'age' variable has a value of %d (%d),\nand its address in RAMemory is %p (%p) [Displayed as d : %d - %d] \n", age, *ptrToAge, &age, (void*)ptrToAge, &age, (void*)ptrToAge);
return 0;
}
and this are my outputs :
Run n
The 'age' variable has a value of 10 (10),
and its address in RAMemory is 0x16d12716c (0x16d12716c) [Displayed as d : 1829925228 - 1829925228]
Run n+1
The 'age' variable has a value of 10 (10),
and its address in RAMemory is 0x16d6d716c (0x16d6d716c) [Displayed as d : 1835889004 - 1835889004]
Of course I have the expected following warnings :
main.c:10:167: warning: format specifies type 'int' but the argument has type 'int *' [-Wformat]
printf("The 'age' variable has a value of %d (%d),\nand its address in RAMemory is %p (%p) [Displayed as d : %d - %d] \n", age, *ptrToAge, &age, (void*)ptrToAge, &age, (void*)ptrToAge);
~~ ^~~~
main.c:10:173: warning: format specifies type 'int' but the argument has type 'void *' [-Wformat]
printf("The 'age' variable has a value of %d (%d),\nand its address in RAMemory is %p (%p) [Displayed as d : %d - %d] \n", age, *ptrToAge, &age, (void*)ptrToAge, &age, (void*)ptrToAge);
~~ ^~~~~~~~~~~~~~~
%dis just undefined behaviour. Pointers andintcan have different sizes. Taking just part of the address will not result in useful output.printfinterprets it as an integer. I don't think even that behavior is guaranteed, and you're lucky to see anything half-predictable here. The value0x16d12716cis not equal to1829925228. That's only true if you discard the high-order bytes: e.g.0x16d12716c & 0xffffffff