I was experimenting with a double pointer(pointer to a pointer) and wanted to understand it properly . I was trying out the following code
#include<stdio.h>
int main()
{
int y = 5;
int *p = &y;
int *q = &p;
printf("\n\n %p %p %p %p %d\n\n",q,&p,p,*q,*p);
return 0;
}
Now in the above code , p is a pointer pointing to y and q is a pointer pointing to p. I have purposely not used a double pointer (**q) ,just to check what happens. The compiler gave me a warning indicating incompatible pointer type . When I executed the code ,I understood that q is a pointer to p ,so it contains the address of p ,but *q is not giving me the value contained in p ,that is the address of y ,rather I got some junk value. Is it because I have not declared q as a double pointer ? Can anyone explain why exactly I am getting some weird value for *q ?
I got some junk value. Is it because I have not declared q as a double pointer ?
In essence, yes: since you declared q
as a pointer to int
, the dereference operation *q
thinks that the address is an int
. When that int
is sent to %p
as a pointer, you hit undefined behavior. Note that the behavior would remain undefined even on platforms where the representation of a pointer is exactly the same as than of an int
. That's the treacherous nature of undefined behavior: sometimes it works "by mistake".
In your example p
is a pointer to an int, which means the &p
is a pointer to a pointer to int. Therefore, q
should be declared as int**
From my comment below... you have declared q
incorrectly... therefore, *q
is an integer, not a pointer, and you are passing an integer into printf()
where it is looking for a memory address... pretty much anything after that is undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With