What is the difference between ->
and .
while calling variables in a structure?I have seen both of them used in various scenarios but couldn't identify the difference between them.
-
3One is used when you have a *pointer* to a structure. The other is when you have an *instance* of a structure. Please [find a good book to read about it](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list). – Some programmer dude Dec 02 '16 at 13:42
4 Answers
->
means you have a variable that points to a piece of memory containing the struct. To access its members, you must dereference the pointer and then add the offset to the member. the->
does that for you.the
.
means your variable is the structure and you only need to add the offset to the member.
As user Eliot B points out, if you have a pointer s
to a struct, then accessing the member elem
can be done in two ways: s->elem
or (*s).elem
.
With (*s)
you have an expression that "is" the struct and you now use the dot-operator to access elem
.

- 25,048
- 4
- 23
- 41
The difference is about the structure's defined instance. '->' and '.' operators is always about the left operand.
If left operand is a pointer, then you use '->', else you use '.'.
For example.
struct Foo bar1;
struct Foo* bar2 = malloc(sizeof(struct Foo));
bar1.variable = "text";
bar2->variable = "text";

- 2,068
- 11
- 22
x->y
(->
is the pointer to member operator) is equivalent to (*x).y
. Because of operator precedence, you can't write *x.y
as that would be evaluated as *(x.y)
.
The former is easier to type and is a lot clearer. It's used when x
is a pointer to a structure containing the member y
.

- 231,907
- 34
- 361
- 483