Loading lessons...
Nested Structures
Nested Structures
A struct can contain other structs. That's nesting - building big types from smaller ones.
A struct inside a struct
struct Address {
char street[50];
int number;
};
struct Person {
char name[50];
struct Address home;
};
The Person struct contains an Address.
Accessing nested fields
Chain the dots:
person1.home.number = 42;
printf("%d", person1.home.number);
Initializing a nested struct
struct Person p = {"Ada", {"Main St", 42}};
Why nesting?
It models reality: a person has an address, an address has a street and number. Nested structs mirror that shape.
TL;DR
- Structs can hold other structs.
- Access nested fields with chained dots.
p.home.numberreads the nested field.- Nesting mirrors real-world relationships.