Search code examples
cpointerscastingsegmentation-faultpointer-to-pointer

why can't i use casting to deal with pointer to pointer variable without using double asterisks? - This is purely academic


I was just trying something to understand pointer to pointer deeply. I write the code below

int x = 20;
int *p0 = &x;
int *p1 = &p0;
printf("*p0 = %d\n", *p0);
printf("**p1 = %d\n", *((int *)*p1));

I thought the output would be

*p0 = 20
**p1 = 20

As *p1 would be evaluated to the address of x as an integer value and then I could use casting to de-reference the value in address x. since the value of *p1 represents a valid memory location of x. But the output was

snapshot from xterm for output of the code

I would like to understand this behavior.

NOTE - this is purely academic, I have no intention to write code this way


Solution

  • I think what you want to know is why this is happening:

    let's say there are 3 boxes of memory

    x y z
    20 &x &y

    why cant you do that *((int *) *z) => => *y => => x

    and the answer is you should compile your code with warning flags and not write code like this!!

    But, you can make it work by casting it as you want to treat it.

    instead of

    printf("**p1 = %d\n", *((int *)*p1));
    

    you should write:

    printf("**p1 = %d\n", *((int *)*((int **)p1)));
    

    z is declared as int * so when you do this z - the compiler knows it's an int not an int so you can't take a 1-byte variable and treat it like it is a 4-byte variable

    and for those who think it cant be compiled: enter image description here