Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer to pointer versus a pointer

Tags:

c

pointers

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 ?

like image 683
user1955184 Avatar asked Apr 12 '13 16:04

user1955184


2 Answers

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".

like image 71
Sergey Kalinichenko Avatar answered Sep 29 '22 00:09

Sergey Kalinichenko


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.

like image 35
K Scott Piel Avatar answered Sep 29 '22 02:09

K Scott Piel