Nested structs
- C course
- Beginner
- Lesson 98/116
- 5 min
Learn to use a struct inside another struct.
Nested structs
A struct member can be another struct. This is very useful to model complex data.
struct Point { int x; int y; };
struct Rectangle {
struct Point topleft;
struct Point bottomright;
};Here Rectangle contains two Points: topleft and bottomright. To reach a nested member you use dots in a chain: r.topleft.x. This is the natural way to represent a rectangle by two corners.
Nested struct example
When declaring a Rectangle variable you can give the inner Points with nested braces.
struct Rectangle r = {
{0, 0},
{10, 5}
};
printf("%d %d\n",
r.topleft.x,
r.bottomright.y);
// "0 5"Here the outer braces wrap the Rectangle, the inner braces wrap each Point. With r.topleft.x you get the top-left corner's x. This structure is very common in graphics and game programming.
Practice Print rectangle corners
Define struct Point (int x, int y). Define struct Rectangle (struct Point topleft, struct Point bottomright). In main create a variable r = {{0, 0}, {10, 5}} and print its four coordinates with printf.
Starter code
#include <stdio.h>
struct Point { int x; int y; };
/* Define struct Rectangle with topleft and bottomright Points */
int main(void) {
/* Create a Rectangle; print its four coordinates with printf */
return 0;
}Sample solution
struct Rectangle { struct Point topleft; struct Point bottomright; };
struct Rectangle r = {{0, 0}, {10, 5}};
printf("%d %d %d %d\n", r.topleft.x, r.topleft.y, r.bottomright.x, r.bottomright.y);Expected output
0 0 10 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match expression to meaning
| Term | Meaning |
|---|---|
r.topleft |
Top-left point |
r.bottomright |
Bottom-right point |
r.topleft.x |
x of top-left |
struct Point |
Inner type |
2 Fill in the blank: nested member
printf("%d
", r____);
printf("%d
", r.topleft.x);
Explanation: r.topleft.x goes down to the nested member.
3 What does r.topleft.x give?
- The x of bottomright
- The x of the topleft point
- The x of Rectangle Correct answer
- A topleft pointer
Explanation: r.topleft.x gives the x of the topleft point.