Cheat Sheets
Structures, Unions, Enums · Study material
C Structures, Unions and Enums Cheat Sheet
| Task | Code |
|---|---|
| Define | struct point { int x, y; }; |
| Initialise | struct point p = {.x = 1, .y = 2}; |
| Member / through pointer | p.x · pp->x |
| Alias | typedef struct point Point; |
| Temporary struct | draw((struct point){3, 4}); |
| Member offset | offsetof(struct point, y) |
| Linked node | struct node { int v; struct node *next; }; |
| Flexible array | struct msg { size_t n; char data[]; }; |
| Union | union num { int i; double d; }; |
| Enum with count | enum color { RED, GREEN, BLUE, COLOR_COUNT }; |
| C23 typed enum | enum e : unsigned char { A, B }; |
| Bit-field | unsigned ready : 1; |
| Type (64-bit) | sizeof |
|---|---|
struct { char a; int b; char c; } | 12 |
struct { int b; char a; char c; } | 8 |
struct { char c; double d; } | 16 |
union { char c; int i; double d; } | 8 |
Padding is real: never write a struct to a file or socket with one fwrite() and expect another compiler to read it the same way.