I want to print where a variable is stored. I Google it and I found this:
int *p;
printf("memory location of ptr: %p\n", (void *)p);
If I write this, is it right?
printf("memory location of ptr: %p\n", &p);
I compiled it and I didn't get any errors or warnings. However, the above two commands didn’t return the same value!
Lets say you have these declarations:
int i;
int *p = &i;
It would look something like this in memory:
+---+ +---+ | p | --> | i | +---+ +---+
If you then use &p
you get a pointer to p
, so you have this:
+----+ +---+ +---+ | &p | --> | p | --> | i | +----+ +---+ +---+
So the value of p
is the address of i
, and the value of &p
is the address of p
. That's why you get different values.