Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

pointers

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

like image 535
Alan Tam Avatar asked Dec 01 '25 14:12

Alan Tam


1 Answers

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.

like image 155
JeremyP Avatar answered Dec 03 '25 10:12

JeremyP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!