Pointers on C——10 Structures and Unions.10

来源:互联网 发布:amd优化游戏 编辑:程序博客网 时间:2024/06/02 07:28

10.2.5 Accessing a Pointer Member

The expression px->d gives the result you would expect—its R‐value is 0, and its L-value is the location itself. The expression *px->d is more interesting. Here indirection is applied to the pointer value found in the member d. But d contains the null pointer,so it doesnʹt point to anything. Dereferencing a null pointer is an error, but as discussed earlier, some environments will not catch it at run time. On these machines,the program will access whatever is at location zero as if it were one of these structures, and then continue merrily on as if nothing were wrong. This example illustrates the importance of checking to see that pointers really point to something before dereferencing them.

表达式px- d 的结果正如你所料——它的右值是0 ,它的左值是它本身的内存位置。表达式*px->d 更为有趣。这里间接访问操作符作用于成员d 所存储的指针值。但d 包含了个NULL 指针,所以它不指向任何东西个NULL 指针进行解引用操作是个错误,但正如我们以前讨论的那样,有些环境不会在运行时捕捉到这个错误。在这些机器上,程序将访问内存位置零的内容,把它也当作是结构成员之,如果系统未发现错误,它还将高高兴兴地继续下去这个例子说明了对指针进行解引用操作之前检查一下它是否有效是非常重要的。


Letʹs create another structure and set x.d to point to it 

让我们创建另个结构,并把x.d 设置为指向它。


Ex x = { 10, "Hi", {5, { -1, 25 } }, 0 };

Ex *px = &x;


Ex y;

x.d = &y;


Now we can evaluate *px->d.

现在我们可以对表达式*px->d 求值


The member d points to a structure, so applying indirection to it yields the entire structure. The new structure was not initialized explicitly, so no values are shown for its members in the diagram.

成员d 指向个结构,所以对它执行间接访问操作的结果是整个结构。这个新的结构并没有显式地初始化,所以在图中并没有显示它的成员的值


As you may expect, members of this new structure can be selected by adding more operators to the expression. We use the arrow because d points to a structure.

What do these expressions accomplish?

正如你可能预料的那样,这个新结构的成员可以通过在表达式中增加更多的操作符进行访问。我们使用箭头操作符,因为d 是个指向结构的指针下面这些表达式是执行什么任务的呢?


px->d->a

px->d->b

px->d->c

px->d->c.a

px->d->c.b[1]


Here is a diagram of the R‐value of the last expression.

最后个表达式的右值可以图解如下:


上一章 Pointers on C——10 Structures and Unions.9

原创粉丝点击