C programming

World of typedefs and structs

Normally you declare a struct type Pos as:

struct Pos { int x; int y; };

Then create a variable myPos as:

struct Pos myPos;
myPos.x = 0;
myPos.y = 1;

You may also initiate it directly:

struct Pos myPos = { 0, 1 };

You can also declare a variable at the same time as the struct type (which is a bit silly):

struct Pos { int x; int y; } myPos;
myPos.x = 0;
myPos.y = 1;

This should also work with initialisation:

struct Pos { int x; int y; } myPos = { 0, 1 };

When using struct with typedef it gets a bit confusing.

Here you create a "shorthand name" PosType for the struct type Pos.

typedef struct Pos { int x; int y; } PosType;

One can argue that you don't gain much when using it in a variable declaration. You only avoid writing out struct which I think is better to keep for understanding.

PosType myPos = { 0, 1 };

Pos and PosType also seem redundant.

If you have a pointer to a struct the member access is different.

struct Pos *myPos = { 0, 1 };
myPos->x = 2;

Or if you want to allocate object on the heap:

struct Pos *myPos; 
myPos = malloc(sizeof(struct Pos));

References