Step 1 of 7
Define a struct
Real data comes in groups. A player has a name, kills and deaths; a point has an x and a y. Keeping them in separate variables means passing three arguments everywhere and hoping they stay in sync. A struct bundles related variables into one new type.
#include <stdio.h>
struct Book {
const char *title;
int year;
double price;
};
int main(void) {
struct Book b = {"The C Programming Language", 1978, 45.0};
printf("%s (%d)\n", b.title, b.year);
b.price = b.price * 0.8;
printf("sale price %.2f\n", b.price);
return 0;
}
The C Programming Language (1978)
sale price 36.00
The parts
struct Book { ... };defines the type: a blueprint listing the members (also called fields). Note the semicolon after the closing brace; forgetting it gives a confusing error on the next line.struct Book bcreates a variable of that type. The type's full name includes the wordstruct.{"...", 1978, 45.0}initializes the members in the order they're declared. You can also name them:{.year = 1978, .title = "...", .price = 45.0}, which is clearer and survives reordering.b.titleuses the dot operator to reach one member. Each member is a normal variable you can read and assign.
In memory
A struct's members are stored together, in declaration order, as one block. The compiler may add a few bytes of padding between members so each is aligned for fast access, which is why sizeof(struct Book) can be larger than the sum of its members.
Your turn: complete the struct and print the weapon's name and damage.