C dot and arrow (. / ->) – this is what I have to perceive

Arrow is just the dot version while accessing elements of a struct/class that is a pointer instead of a reference.

struct foo
{
  int x;
  float y;
};

struct foo var;
struct foo* pvar;
pvar = malloc(sizeof(struct foo));

var.x = 5;
(&var)->y = 14.3;
pvar->y = 22.4;
(*pvar).x = 6;

Why parenthesis are in use?

. is standard member access operator that has a higher precedence than * pointer operator.

To make the compiler know that dereference acts on the struct, but not on the element, the parethesis have to be added properly.

Based on discussion.

This entry was posted in c, programming. Bookmark the permalink.