what's the difference about p.a and p->a where p is pointer?
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
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.
Yes, you can't do p.a
on a pointer, the dot operator requires an actual instance, i.e. a value of the proper struct
type.
Note that "under the hood", p->a
is equivalent to (*p).a
, but easier to type and read. Nobody ever uses the latter form, but it's sometimes handy as a way of understanding what the arrow operator does.
try (*p).a or (&p)->a where p is a pointer and an instance respectively ;-)
If p is a pointer then p.a isn't valid syntax.
It's compile time error.. p->a is valid only.
精彩评论