I have stored the address of a integer variable in a pointer and then store the address of that previous into another pointer.I am not able to understand how it actually works.
#include <iostream>
using namespace std;
#include <stdio.h>
int main ()
{
int var;
int *ptr;
int **pptr;
var = 30;
/* take the address of var */
ptr = &var;
/* take the address of ptr using address of operator & */
pptr = &ptr;
/* take the value using pptr */
printf("Value of var = %d\n", var );
printf("Value available at ptr = %d\n", ptr );
printf("Value available at pptr = %d\n", pptr);
return 0;
}
When you do &ptr
you get the address of the variable ptr
is stored.
So you have a pointer pptr
which points at ptr
which in turn point at var
. Like this:
+------+ +-----+ +-----+ | pptr | --> | ptr | --> | var | +------+ +-----+ +-----+
On a side-note, don't use the "%d"
format to print pointers. Use "%p"
instead, and then cast the pointers to void *
.