Pointer to pointer versus pointer

I experimented with a double pointer (pointer to pointer) and wanted to understand it correctly. I tried 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 specifically did not use a double pointer (** q) to check what was happening. The compiler gave me a warning indicating an incompatible pointer type. When I executed the code, I realized that q is a pointer to p, so it contains the address p, but * q does not give me the value contained in p, that is, the address y, rather I got some spam value, This is because I did not declare q as a double pointer? Can someone explain why I get some weird value for * q?

+5
4

- . , q ?

, : q int, *q , int. int %p , undefined. , undefined , , int. undefined: " ".

+3

p int, , &p int. q int**

... q... *q , , printf(), ... undefined .

+1

 int *q = &p;

& p - (p), int (y)

int (q)

* q p . , y (= 5)

+1

- , - *q?

:

  • -, *q, int. .
  • Secondly, your format specifier printf()does not match the type of the fifth argument.

On some platforms (including the computer I'm typing this on) the pointer is wider than int. If I run my code on my computer, I get:

0x7fff5ef94ad8 0x7fff5ef94ad8 0x7fff5ef94ae4 0x5ef94ae4 5

Here, the 64-bit pointer is truncated to 32-bit int. Therefore, only the bottom of the pointer is displayed. However, since the behavior of your code is undefined, it might fail in other ways.

+1
source

All Articles