Pointers on C——6 Pointers.10

​6.10 Pointers to Pointers

We will spend only a brief moment here on an example that suggests topics to come.Consider these declarations:

这里我们再稍微花点时间来看一个例子,揭开这个即将开始的主题的序幕。考虑下面这些声明:


int a = 12;

int *b = &a;


They allocate memory as shown in the following diagram:

它们如下图所示进行内存分配:


Suppose we had a third variable called c and initialized it with this statement;

假定我们又有了第3 个变量,名叫c ,并用下面这条语句对它进行初始化:

c = &b;

Here is what memory would look like:

它们在内存中的模样大致如下:


The question is; what is the type of c? Clearly it is a pointer, but what does it point to?The variable b is a ʺpointer to an integer,ʺ so anything that points to b must be a pointer to a ʺpointer to an integer,ʺ or more generally, a pointer to a pointer.

问题是: C 的类型是什么?显然它是一个指针,但它所指向的是什么?变量b 是一个"指向整型的指针",所以任何指向b 的类型必须是指向"指向整型的指针"的指针,更通俗地说,是一个指针的指针。


Is this legal? Yes! A pointer variable is like any other variable in that it occupies a specific location in memory, so it makes sense that we can obtain its address with the & operator.

它合法吗?是的!指针变量和其他变量一样,占据内存中某个特定的位置,所以用&操作符取得它的地址是合法的1 。


How would this variable be declared? The declaration

那么这个变量是怎样声明的呢?声明

int **c = &b;


says that the expression **c is of type int. Table 6.1 lists some expressions that may help illustrate this concept; the expressions assume these declarations.

表示表达式**c 的类型是int 。表6.1 列出了一些表达式,有助于我们弄清这个概念。假定这些表达式进行了如下这些声明。


int a = 12;

int *b = &a;

int **c = &b;


The only new expression in the table is the last one, so letʹs unravel it. The * operator has right‐to‐left associativity, so this expression is equivalent to *(*c). We must evaluate it from the inside out. *c takes us co the location to which c points, which we know to be the variable b. The second indirection then takes us to where this location points, which is a. The only thing tricky about pointers to pointers is keeping all of the arrows straight and remembering that an arrow is followed only if an indirection operator causes it.

表中唯一的新面孔是最后一个表达式,让我们对它进行分析。*操作符具有从右向左的结合性,所以这个表达式相当于*俨吟,我们必须从里向外逐层求值。*c 访问c 所指向的位置,我们知道这是变量b 。第2 个间接访问操作符访问这个位置所指向的地址,也就是变量a 。指针的指针并不难懂,你只要留心所有的箭头,如果表达式中出现了间接访问操作符,你就随箭头访问它所指向的位置。

上一章 Pointers on C——6 Pointers.9


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值