value = 32 *pv = 2293624 **ppv = 2293624
#include <stdio.h> void main ( void ) { int value; int *pv; int **ppv; value = 32; pv = (int *)&ppv; ppv = &pv; printf("value = %d\n", value ); printf("*pv = %d\n", *pv ); printf("**ppv = %d\n", **ppv ); system("pause"); }
What is going on?
The programmer put the address of ppv
into pv
, and
then put the address of pv
into ppv
. The compiler
would not let you do this:
pv = &ppv;
because pv
has been declared to contain the address of an int
variable, and ppv
has not been declared to be an int
variable. But this type cast tells the compiler to go ahead anyway:
pv = (int *)&ppv;
So now both pv and ppv contain addresses of something. This statement:
printf("*pv = %d\n", *pv );
prints out the contents of what pv
points to. pv
points
to something that contains an address, and so that address is printed out (using
decimal):
*pv = 2293624
Slightly more tricky is this:
printf("**ppv = %d\n", **ppv );
*ppv
follows the pointer in ppv
to pv
,
then **ppv
follows the address there back to ppv
and
gets whatever is there. What is there is the address of pv
and
so that is printed out:
**ppv = 2293624
It might help to redraw the diagram showing the variables as memory with addresses in decimal:
All I really know is that pv
is at address 2293624 in one particular
run of the program. I've guessed at the other addresses.
So this statement:
printf("*pv = %d\n", *pv );
means go to pv
and get the address there ( 2293628 ) and then
go to that address and get the value there ( 2293624 ) and then print out that
value.
Now this statement:
printf("**ppv = %d\n", **ppv );
means go to ppv
and get the address there ( 2293624 ) and then
go to that address and get the address there ( 2293628) and then go to that
address and get the value there (2293624 ) and print out that value.