Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top