Is a pointer variable also assigned a memory address?

狂风中的少年 提交于 2020-01-04 03:01:28

问题


In C++, on the stack, a simple variable is assigned a memory address so that we can use a pointer to contain this memory to point to it; then is a pointer also assigned a memory address?

If yes, can we have a pointer of pointers?


回答1:


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: Is primitive assigned a memory address?, 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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/329399/is-a-pointer-variable-also-assigned-a-memory-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!