-6

In a C program, when i define a struct.

under which circumstances would i use "->" and under which "." ?

for example

typedef struct foo foo;

struct foo{

  double bar;
  double bar2;
}

foo barbar;

when would I use barbar.bar and when would i use barbar->bar ?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Lena Bru
  • 13,521
  • 11
  • 61
  • 126
  • 4
    This is a much-too-basic C question. Please consult your local C reference book. – Daniel Kamil Kozar May 09 '14 at 16:02
  • 2
    `->` for pointers, `.` for instances. Also, as Daniel pointed out, basic C pointer question. Should be found in any good book or tutorial. – AntonH May 09 '14 at 16:02
  • 2
    possible duplicate of [Arrow operator (->) usage in C](http://stackoverflow.com/questions/2575048/arrow-operator-usage-in-c) – Paul R May 09 '14 at 16:03
  • 1
    duplicate of http://stackoverflow.com/questions/1238613/what-is-the-difference-between-the-dot-operator-and-in-c – phuclv May 09 '14 at 16:07
  • 1
    `a->b` is *exactly the same* as `(*a).b`, so the answer is: you would use `->` any time you would use `(*a).b`. If you don't understand what `*a` means then you need to go back a step and learn about the fundamental relationships between *storage* and *pointers*. `&` turns *storage* into a *pointer*, and `*` turns a *pointer* back into *storage*. Make sure you understand this at a deep level before you continue. – Eric Lippert May 09 '14 at 16:14

2 Answers2

2

Left of -> should be pointer type, while normal variables/instances for ..

  • If you have a struct foo myFoo, you should use myFoo. or (&myFoo)->.
  • If you have a struct foo *myFoo, you should use myFoo-> or (*myFoo)..
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
1

Use a -> for a pointer to a struct as it dereferences the pointer, use a . for a struct

jayjay
  • 1,017
  • 1
  • 11
  • 23