Question

While it may be very obvious to those familiar with C and its nuances, I'm not as familiar with either and can't tell if there is any significant difference between accessing a struct's member using -> or ..

Like if I have struct my_struct:

struct my_struct {
  int x;
  int y;
};

struct my_struct grid;

Does it make a difference, beyond differing syntax, whether I access struct my_struct grid's x member via grid.x or grid->x? And if there is a difference, which one should I prefer?

Tried searching google/SO, but I didn't find anything that mentioned which one was the preferred, if any, method. Both seem correct, but I can't help but feel that one of them (->) has a more specialized use-case.

Was it helpful?

Solution

It depends on how the struct is declared. If we have an actual struct variable, use .. If we have a pointer to a struct, use ->:

struct my_struct *s = ...;
s->x = 5;
printf("%d\n", s->x);

struct my_struct s2 = ...;
s2.x = 4;
printf("%d\n", s2.x);

OTHER TIPS

x->foo

is shorthand for:

(*x).foo

which, as others have observed, only makes sense if x is a pointer to a struct.

A simple rule to remember when to use '.' and when to use '->' (generally)...

abc->def   or   abc.def

When 'abc' is defined as a pointer, use '->':

struct XYZ
   {
   int def;
   } *abc;

abc->def = 1;  

When 'abc' is not defined as a pointer, use '.':

struct XYZ
   {
   int def;
   } abc;

abc.def = 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top