> Struct C question?

Struct C question?

Posted at: 2014-12-18 
If your struct is defined as such:

struct structType{

int a;

int b;

}

If you declare your structure as such:

struct structType my_struct;

then you reference the members using

my_struct.a;

If you declare your structure as a pointer (and hopefully points to some properly allocated memory location):

struct structType *my_struct;

then you reference the members using

my_struct->a;

If the code you are writing has direct access to the object instance itself, by name, then you may use the "." notation to access a member of the object. If the code you are writing was provided only with a pointer to the object instance, and doesn't have the actual object instance itself in scope, then you use the "->" notation to access members. It's possible that you have both a pointer to the object AND the object itself in scope -- in that case you can go either way, but the "." notation will usually be more efficient then.

For example:

? ? ? ? {

? ? ? ? ? ? struct { int a, b; } x, *y= &x;

? ? ? ? ? ? x.a= 1; ? ? // not, x->a= 1;

? ? ? ? ? ? y->b= 2; ? ? ? ?// not, y.a= 2;

? ? ? ? }

In the above, you have x, which IS the object, and you have y, which is a pointer TO the object. There is ONLY one object here. Not two. y just points at x. So, when using the object directly, the dot (.) syntax is used. But when using a pointer TO the object instead, the arrow (->) syntax is used.

node->x means a pointer to x in the node struct.

node.x means the value of x in the node struct.

-> is the structure dereference operator

Structure dereference ("member b of object pointed to by a")

node->x

node is a pointer to a structure

node.x

node is a structure