10.1.4 Indirect Member Access
How do you access the members of a structure if all you have is a pointer to it? The first step is to apply indirection to the pointer, which takes you to the structure. Then you use the dot operator to select a member. However, the dot operator has higher precedence than the indirection, so you must use parentheses to ensure that the indirection is evaluated first. As an example, suppose an argument to a function is a pointer to a structure, as in this prototype:
如果你拥有一个指向结构的指针,你该如何访问这个结构的成员呢?首先就是对指针执行间接访问操作,这使你获得这个结构。然后你使用点操作符来访问它的成员。但是,点操作符的优先级高于间接访问操作符,所以你必须在表达式中使用括号,确保间接访问首先执行。举个例子,假定一个函数的参数是个指向结构的指针,如下面的原型所示:
void func( struct COMPLEX *cp );
The function can access the member f of the structure to which this variable points with this expression:
函数可以使用下面这个表达式来访问这个变量所指向的结构的成员f:
(*cp).f
The indirection follows the pointer to the structure; once there the dot operator selects a member.
对指针执行间接访问将访问结构,然后点操作符访问一个成员。
Because this notation is a nuisance, C provides a more convenient operator to do this job—the‐> or arrow operator. Like the dot, the arrow takes two operands, but the left operand must be a pointer to a structure! The arrow operator applies indirection to the left operand to follow the pointer, and then selects the member specified by the right operand exactly like the dot operator. The indirection is built into the arrow operator, though, so we donʹt need an explicit indirection or the accompanying parentheses. Here are a few examples using the same pointer as before.
由于这个概念有点惹人厌,所以C 语言提供了一个更为方便的操作符来完成这项工作—— ->操作符(也称箭头操作符)。和点操作符一样,箭头操作符接受两个操作数,但左操作数必须是一个指向结构的指针。箭头操作符对左操作数执行间接访问取得指针所指向的结构,然后和点操作符一样,根据右操作数选择一个指定的结构成员。但是,间接访问操作内建于箭头操作符中,所以我们不需要显式地执行间接访问或使用括号。这里有一些例子,像前面一样使用同一个指针。
cp->f
cp->a
cp->s
The first expression accesses the floating‐point member. The second is an array name,and the third is a structure. Shortly you will see numerous additional examples to clarify accessing structure members.
第1 个表达式访问结构的浮点数成员,第2 个表达式访问一个数组名,第3 个表达式则访问一个结构。你很快还将看到为数众多的例子,可以帮助你弄清如何访问结构成员。