-2

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.

Jeyaram
  • 9,158
  • 7
  • 41
  • 63
Govindh
  • 67
  • 1
  • 10
  • 3
    One 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 Answers4

2
  • -> 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.

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
1

s->elem is equal to (*s).elem

https://en.wikipedia.org/wiki/Dereference_operator

Eliot B.
  • 162
  • 11
1

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"; 
cokceken
  • 2,068
  • 11
  • 22
1

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483