I am currently learning C by reading a good beginner's book called "Teach Yourself C in 21 Days" (I have already learned Java and C# so I am moving at a much faster pace). I was reading the chapter on pointers and the -> (arrow) operator came up without explanation. I think that it is used to call members and functions (like the equivalent of the . (dot) operator, but for pointers instead of members). But I am not entirely sure. Could I please get an explanation and a code sample?
+9
A:
foo->bar
is equivalent to (*foo).bar
, i.e. it gets the member called bar
from the struct that foo
points to.
sepp2k
2010-04-04 16:23:03
+6
A:
Yes, that's it.
It's just the dot version when you want to access elements of a struct/class that is a pointer instead of a reference.
struct foo
{
int x;
float y;
};
struct foo var;
struct foo* pvar;
var.x = 5;
(&var)->y = 14.3;
pvar->y = 22.4;
(*pvar).x = 6;
That's it!
Jack
2010-04-04 16:23:31
Just to point it out (no pun intended), you forgot the ; at the end bracket of the struct, it should be };
Mohit Deshpande
2010-04-04 16:30:06
incredible, I was editing it while you were writing the comment.. precog!
Jack
2010-04-04 16:30:37
+3
A:
a->b
is just short for (*a).b
in every way (same for functions: a->b()
is short for (*a).b()
).
Peter Alexander
2010-04-04 16:23:41
+2
A:
foo->bar
is only shorthand for (*foo).bar
. That's all there is to it.
Matti Virkkunen
2010-04-04 16:23:57