Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between pointers to variables, and pointers to structures in C

In learning C, I've just begun studying pointers to structures and have some questions.

Suppose I were to create a structure named myStructure, and then create a pointer myStructurePointer, pointing to myStructure. Is *myStructurePointer, and myStructure two ways of referencing the same thing? If so, why is it necessary to have the -> operator? It seems simpler to use *myStructurePointer.variable_name than myStructurePointer->variable_name.

like image 384
objectivesea Avatar asked Feb 20 '10 01:02

objectivesea


2 Answers

You're right,

(*structurePointer).field

is exactly the same as

structurePointer->field

What you have, however, is :

*structurePointer.field

Which really tries to use the . operator on the pointer variable, then dereference the result of that - it won't even compile. You need the parentheses as I have them in the first example above if you want the expressions to be equivalent. The arrow saves at least a couple of keystrokes in this simple case.

The use of -> might make more sense if you think about the case where the structure field has pointer type, maybe to another structure:

structurePointer->field->field2

vs.

(*(*structurePointer).field).field2
like image 50
Carl Norum Avatar answered Sep 29 '22 08:09

Carl Norum


The problem with *myStructurePointer.variable_name is that * binds less tight than ., so it would be interpreted as *(myStructurePointer.variable_name). The equivalent of myStructurePointer->variable_name would be (*myStructurePointer).variable_name, where the parenthesis are required.

There is not difference between a->b and (*a).b, but -> is easier to use, especially if there are nested structures. (*(*(*a).b).c).d is much less readable than ´a->b->c->d`.

like image 20
sth Avatar answered Sep 29 '22 07:09

sth