指针变量也被分配了一个内存地址吗? [英] Is a pointer variable also assigned a memory address?

查看:137
本文介绍了指针变量也被分配了一个内存地址吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,在堆栈上,为一个简单的变量分配了一个内存地址,以便我们可以使用指针来包含该内存以指向它;那么指针还被分配了一个内存地址吗?

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?

推荐答案

是的,您是正确的.我们可以使用指向指针的指针:

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;

从右到左读取它: ppa是一个指向int的指针.不限于**.您可以根据需要设置任意多个级别. int ***将是指向int 的指针的指针.

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.

这篇关于指针变量也被分配了一个内存地址吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆