Structs in C
Grouping data with struct in C, the dot and arrow operators, typedef, and passing structs to functions.
A struct groups related values into one type. Access fields with . on a struct and -> on a pointer to a struct (p->x is short for (*p).x).
Structs are copied when passed by value, which is fine for small ones. For big structs, or when the function should change the original, pass a pointer (a const pointer if it only reads).
typedef struct { ... } Point; lets you write Point instead of struct point.
Example
#include <stdio.h>
typedef struct {
char name[16];
int hp;
} Player;
void hit(Player *p, int dmg) {
p->hp -= dmg;
}
int main(void) {
Player p = {"Ada", 100};
hit(&p, 30);
printf("%s has %d hp\n", p.name, p.hp);
return 0;
}
Output:
Ada has 70 hp
Watch it run: Structs and the arrow operator