what's the difference about p.a and p->a where p is pointer?

旧时模样 提交于 2021-01-27 12:52:57

问题


Is there any difference about p.a and p->a where p is pointer? or they are just same thing.


回答1:


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.




回答2:


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.




回答3:


try (*p).a or (&p)->a where p is a pointer and an instance respectively ;-)




回答4:


If p is a pointer then p.a isn't valid syntax.




回答5:


It's compile time error.. p->a is valid only.



来源:https://stackoverflow.com/questions/5649619/whats-the-difference-about-p-a-and-p-a-where-p-is-pointer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!