views:

890

answers:

3

In C++:

On stack, a simple variable is assigned a memory address so that we can use pointer to contain this memory to point to it; then is a pointer also assigned a memory address? if yes, we can have pointer of pointers now?

Thanks!

+12  A: 

Yes, you are right. We can have pointers to pointers:

int a;
int b;
int * pa = &a;
int ** ppa = &pa;

// set a to 10
**ppa = 10;

// set pa so it points to b. and then set b to 11.
*ppa = &b;
**ppa = 11;

Read it from right to left: ppa is a pointer to a pointer to an int . It's not limited to ** . You can have as many levels as you want. int *** would be a pointer to pointer to pointer to int .

I answered a similar question regarding whether primitive variables have addresses here: http://stackoverflow.com/questions/316194/is-primitive-assigned-a-memory-address#316310, the same applies to pointers too. In short, if you never take the address of an object, the compiler doesn't have to assign it an address: It can keep its value in a register.

Johannes Schaub - litb
+9  A: 

Yes, you can have pointers to pointers (or pointers to pointers to pointers), and yes, when necessary, pointers are also stored at an address in memory.

However, as with all stack variables, the compiler is free to avoid writing the data to memory, if it can determine that it's not necessary. If you never take the address of a variable, and it doesn't have to outlive the current scope, the compiler may just keep the value in a register.

jalf
+1  A: 

Pointer is just a variable (memory location) that stores the address of other variables. Its own address can ofcourse be stored somewhere else.

Sridhar Iyer