Reputation: 155
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;
}
Upvotes: 0
Views: 69
Reputation: 106012
This ASCII art will help you to understand
pptr ptr var
+----------+ +----------+ +-----------+
| | | | | |
| 0x67890 +------> | 0x12345 +------> | 30 |
| | | | | |
+----------+ +----------+ +-----------+
0xABCDE 0x67890 0x12345
Upvotes: 1
Reputation: 534
Let's say var
is stored at the memory address 0x12345678, ptr
at the address 0x23456789 and pptr
at the address 0x34567890.
When you do
var = 30;
you store 30 in the value of var (at the address of var, 0x12345678
)
When you do
ptr = &var;
you store the address of var in the value of ptr. When you do
pptr = &ptr;
you store the address of ptr in the value of pptr.
The memory looks like this
Address Value stored
...
0x12345678 30
...
0x23456789 0x12345678
...
0x34567890 0x23456789
If you try to print pptr
, it will show 0x23456789
If you try to print *pptr
, it will show the value at the address corresponding to the value of pptr
, 012345678
And if you try to print **pptr
, it will show the value at the address corresponding to the value at the address corresponding to the value of pptr
, 30
Upvotes: 2
Reputation: 409196
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 *
.
Upvotes: 5