tags:

views:

622

answers:

5

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
+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
Just to point it out (no pun intended), you forgot the ; at the end bracket of the struct, it should be };
Mohit Deshpande
incredible, I was editing it while you were writing the comment.. precog!
Jack
+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
+2  A: 

foo->bar is only shorthand for (*foo).bar. That's all there is to it.

Matti Virkkunen
+1  A: 

Get a better book.

http://norvig.com/21-days.html

joshperry