问题描述
p.a 和 p->a 有什么区别,其中 p 是指针吗?或者他们只是一回事.
Is there any difference about p.a and p->a where p is pointer? or they are just same thing.
推荐答案
.
运算符实际上是结构成员访问的运算符.
The .
operator is actually the operator for structure member access.
struct Foo
{
int bar;
int baz;
} aFoo;
aFoo.bar = 3;
如果您有一个指向结构的指针,(非常常见)您可以使用指针解引用和 .
运算符访问其成员.
If you have a pointer to a struct, (very common) you can access its members using pointer dereferencing and the .
operator.
struct Foo *p;
p = &aFoo;
(*p).baz = 4;
需要括号是因为 .
比 *
具有更高的优先级.上面取消引用某个结构的成员是非常常见的,因此 ->
被引入作为速记.
The parentheses are needed because .
has higher precendence than *
. The above dereferencing a member of a structure pointed to by something is extremely common, so ->
was introduced as a shorthand.
p->baz = 4; // identical to (*p).baz = 4
如果 p 是一个指针,你永远不会在普通 C 中看到 p.anything
,至少在任何编译器中都不会看到.然而,它在 Objective-C 中用于表示属性访问,这是 IMO 的错误.
If p is a pointer, you never see p.anything
in plain C, at least not in anything that compiles. However, it is used to denote property access in Objective-C which was a mistake IMO.
这篇关于p.a 和 p->a 有什么区别,其中 p 是指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!