Nested structs
- C course
- Intermediate
- Lesson 33/116
- 5 min
Learn nested structs and composition.
Nested structs
A struct can contain another struct type. This is called a nested struct. It's the natural way to break data into meaningful parts.
Example: struct Date { int day, month, year; }; and struct Event { char title[64]; struct Date when; };. Here the when field is a struct Date. Access chains with dots: e.when.day. The inner struct must be defined first; that's how the compiler knows its size. This pattern provides composition when modeling data.
Nested struct example
Nested structs are useful when modeling real-world data. For example, a person's address can be a separate struct.
Example: struct Address { char city[32]; int zip; }; and struct Person { char name[32]; struct Address addr; };. City access: p.addr.city. This structure embeds the address inside the person; it groups it in one struct. If the address is used elsewhere, the same struct Address definition can be reused. Modularity improves and code duplication drops.
Practice Create an event with a date
Define struct Date with int day, month, year;. Define struct Event with char title[64]; and struct Date when;. In main, write struct Event e;; assign e.when.day = 15;, e.when.month = 3;, e.when.year = 2025;. Print with printf("%d.%d.%d\n", e.when.day, e.when.month, e.when.year);.
Starter code
#include <stdio.h>
// Define struct Date (day, month, year)
// Define struct Event (title[64] and struct Date when)
// In main declare e, assign when fields, print the date
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
struct Date {
int day, month, year;
};
struct Event {
char title[64];
struct Date when;
};
int main(void) {
struct Event e;
e.when.day = 15;
e.when.month = 3;
e.when.year = 2025;
printf("%d.%d.%d\n", e.when.day, e.when.month, e.when.year);
return 0;
}Expected output
15.3.2025
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How to access day inside when inside e?
- e.when->day
- e->when.day
- e.when.day Correct answer
- when.e.day
Explanation: Nested struct access chains with dots.
2 Match the access forms
| Term | Meaning |
|---|---|
e.when.day |
Nested field access |
e.when |
Inner struct variable |
struct Date |
Inner struct type |
e.title |
Outer struct field |
3 Assign a nested field
struct Event e;
e____.day = 15;
struct Event e;
e.when.day = 15;
Explanation: e.when.day gives nested access.