-2

i am trying to understand what is the difference when using structs and typedefs to access some components

what is the difference between using the dot operator when dealing with structs using the example below

so far i have tried this code

typedef struct _game{
   int something;
   char something_else;
} g;

if i use

g.something or g->something 

what is the difference?

i have used both of them and they both return results but i still dont understand the difference

can somebody please explain this?

yukapuka
  • 87
  • 1
  • 2
  • 8
  • 1
    Voting to close. This is a duplicate of a duplicate. – Carey Gregory May 09 '14 at 17:43
  • 1
    `g` is a type name, so it can't be the prefix of either `.` or `->`. The prefix of `.` must be an *expression* of struct or union type. The prefix of `->` must be an expression of pointer to struct or pointer to union type. There are not interchangeable; there is no context in which both are valid. The difference between `.` and `->` is explained in any decent C textbook, reference, or tutorial. Please do a little research before posting a question here. – Keith Thompson May 09 '14 at 18:13

1 Answers1

0

I'm assuming this is C. When asking language questions tag the language. There are many languages that look the same and can give you subtly different answers. C++ is a different language than C, btw.

In this statement,

typedef struct _game { int something; } g;

g is a type, not a variable. As such, g.something makes no sense. typedef means "type define". Instead, you would have

g my_g_instance;
g *my_g_ptr = &my_g_instance;

my_g_instance.something = 2;
my_g_ptr->something = 5;

The difference between . and -> is whether the variable to the left of the operator is a pointer or not.

Adam
  • 16,808
  • 7
  • 52
  • 98
  • what if you declare a struct like this `struct _game{int something};` and then this `struct _game *Game;` – yukapuka May 09 '14 at 19:31
  • what about it? That's perfectly fine. Without a typedef, the name of the type is "`struct _game`". – Adam May 09 '14 at 20:03