Home > Mobile >  why can't i use casting to deal with pointer to pointer variable without using double asterisks
why can't i use casting to deal with pointer to pointer variable without using double asterisks

Time:07-17

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

CodePudding user response:

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

CodePudding user response:

This line is not valid C or C :

int *p1 = &p0;

The fact that you say you have compiled and run this code means that you have not turned on error checking in your compiler. You really must do that, otherwise you will write all kinds of code with undefined behavior which can crash or worse.

If you use GCC or Clang, run it with -Wall -Wextra -Werror. Then it will not compile your erroneous code.

  • Related