Structures Inside Structures
A member of a structure can have any type, including an array or another structure. You have already done that with every char name[20]: that is an array inside a structure. An array of numbers works the same way. And when several values inside a structure belong together, such as the day, month and year of a date, you can make them a structure of their own:
typedef struct {
int day;
int month;
int year;
} Date;
typedef struct {
char name[20];
Date birthday;
int points[3];
} Player;A Player of a basketball team has a name, a birthday of type Date, and the points from their last three games. Date must be defined above Player: the compiler reads the program from the top, and it must know Date when it gets to the member birthday.
When you create a player, the inner structure and the inner array each get their own curly braces:
Player eva = {"Eva", {14, 3, 2011}, {12, 8, 15}};To get to an inner value, chain the dots and square brackets, and read them from left to right. eva.birthday is a whole Date, so eva.birthday.year is its year. eva.points is an array, so eva.points[0] is its first element:
printf("%s was born in %d.\n", eva.name, eva.birthday.year);
printf("Points in the first game: %d\n", eva.points[0]);This prints:
Eva was born in 2011.
Points in the first game: 12You go through the inner array with a loop, as through any other array:
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += eva.points[i];
}
printf("Points in total: %d\n", sum);This prints:
Points in total: 35When you skip a step in the chain, as in eva.year, the compiler tells you that a Player has no member year. It's right: the year is a member of Eva's birthday, not of Eva.
main.c:17:50: error: no member named 'year' in 'Player'Instructions
Zara, the hero of a game, walks three steps to the right. Below the printf, add 3 to the x of her position: x is a member of position, which is a member of zara. Then print her position as Position: 5, 5, reading both numbers from the members.
Zara collected coins in three levels of the game, and they are in the array coins. At the end of main (before return 0;), add them up with a loop and print Coins: 21.
Start programming for free
5/9