9.3 Nested Structs and Arrays of Structs
A struct can contain another struct. This is composition, and it lets you split complex data into clearer smaller pieces.
c
typedef struct {
int year;
int month;
int day;
} Date;
typedef struct {
char name[32];
Date birthday;
int score;
} Student;Access nested members by continuing to use .:
c
Student s = {"Ada", {1815, 12, 10}, 96};
printf("%d\n", s.birthday.year); // 1815Put many records into an array of structs to process them like a table:
c
Student class[3] = {
{"Ada", {1815, 12, 10}, 96},
{"Bob", {2000, 1, 1}, 88},
{"Cher", {1999, 5, 9}, 73}
};
for (int i = 0; i < 3; i++) {
printf("%s %d\n", class[i].name, class[i].score);
}A struct such as Date can also be reused inside several other structs, which keeps relationships between types clearer.
Loading interactive lab...
Loading concept check...
Loading practice...