C Nested Structures
A structure can contain another structure as one of its members. This is called nesting, and it lets you model real-world things that naturally have parts within parts, such as an employee who has an address, or a rectangle made from two points.
Putting a struct inside a struct
To nest structures, first define the inner one, then use it as the type of a member in the outer one. When you want to reach a deeply held value, you chain the dot operator to step in one level at a time.
A struct that contains another struct
#include <stdio.h>
struct Address {
char city[20];
int zip;
};
struct Employee {
char name[20];
struct Address addr;
};
int main() {
struct Employee e = {"Anita", {"Delhi", 110001}};
printf("%s lives in %s\n", e.name, e.addr.city);
printf("Zip code: %d\n", e.addr.zip);
return 0;
}Notice how e.addr.city walks from the employee, into the address member, and finally to the city field. Each dot moves one level deeper. The initializer uses nested braces to match the nested layout.
Assigning nested members
You can also fill in nested members after creating the variable. Just chain the dots on the left side of the assignment to reach exactly the field you want.
Updating a nested field
#include <stdio.h>
struct Point {
int x;
int y;
};
struct Rectangle {
struct Point topLeft;
struct Point bottomRight;
};
int main() {
struct Rectangle r;
r.topLeft.x = 0;
r.topLeft.y = 10;
r.bottomRight.x = 5;
r.bottomRight.y = 0;
printf("Top-left x = %d\n", r.topLeft.x);
printf("Bottom-right y = %d\n", r.bottomRight.y);
return 0;
}- Define the inner structure before the outer one that uses it.
- Chain dots (outer.inner.member) to reach nested values.
- Nested initializers use matching nested braces.
- Nesting can go several levels deep, though two or three is usually plenty.