C, lesson 10
A game character has a name, a level and some health. A book has a title, an author and a year. Keeping each of these in separate variables quickly gets messy. A struct bundles related values, called members, into one new type.
This only describes the shape; it doesn't create a book yet. The type's name is
struct book, and you create variables of it like any other type:
The dot operator . reaches a member: favourite.year is an ordinary int you can read,
assign and pass around.
Listing values in order is fragile: swap two members in the struct and every initializer silently changes meaning. Designated initializers name the members instead, in any order. Members you don't mention are set to zero:
Writing struct every time is a little noisy. gives the type a one-word alias. Many
C programmers use it for small value-like types:
2 exercises to try what you just read.
typedefBoth styles are common. Pick one per project and use it consistently.
Assigning one struct to another copies every member, including arrays inside it. Passing a struct to a function also copies it, and a function can return a struct:
(Point){...} is a compound literal: an unnamed struct value built on the spot.
Copying is fine for small structs. For big ones, or when a function must change the caller's
struct, you pass a pointer instead and use the arrow operator, p->x (shorthand for (*p).x).
The pointers lesson explains this fully; for now, remember . for a struct and -> for a
pointer to one.
Structs cannot be compared with ==. Compare the members you care about.
An array of structs is a simple table of records, the C version of a list of objects:
An enum names a small set of integer constants. It pairs well with structs for members that
can only take a few values:
Define a struct film with a title (one word, at most 40 characters), a release year and a
rating (a double). Read a count n (1 to 50), then n lines of title year rating. Store
them in an array of structs, then print the highest-rated film (the first one if several tie)
and how many films came out before the year 2000.
Use this struct for a length of time:
Write two functions: Duration add(Duration a, Duration b), which returns the sum with
seconds always between 0 and 59, and int total_seconds(Duration d).
Read lap times in the form m:ss until the input ends (read each with scanf("%d:%d", ...)).
Print the number of laps, the total time as m:ss, and the fastest lap as m:ss. Seconds
always use two digits. If there are no laps, print only Laps: 0.
struct book {
char title[64];
char author[48];
int year;
};struct book favourite = {"Dune", "Frank Herbert", 1965};
printf("%s (%d)\n", favourite.title, favourite.year);struct book draft = {.year = 2026, .title = "My Novel"}; // author is ""
struct book empty = {}; // C23: everything zerotypedef struct {
double x;
double y;
} Point;
Point origin = {0.0, 0.0};Point midpoint(Point a, Point b) {
return (Point){(a.x + b.x) / 2, (a.y + b.y) / 2};
}struct book shelf[3] = {
{"Dune", "Frank Herbert", 1965},
{"Emma", "Jane Austen", 1815},
{"Neuromancer", "William Gibson", 1984},
};
for (int i = 0; i < 3; i++) {
if (shelf[i].year < 1900) {
printf("Classic: %s\n", shelf[i].title);
}
}enum suit { HEARTS, DIAMONDS, CLUBS, SPADES };
struct card { int rank; enum suit suit; };Input:
3
Alien 1979 8.5
Up 2009 8.3
Heat 1995 8.3
Output:
Best: Alien (1979) rated 8.5
Before 2000: 2typedef struct {
int minutes;
int seconds;
} Duration;Input:
1:45
2:05
1:39
Output:
Laps: 3
Total: 5:29
Best: 1:39