C Nested Structures
A structure member can be of any type — including another structure. Structures inside structures are called nested structures. They let you build bigger data types out of smaller, reusable pieces, the same way a real address is part of a person, and a date is part of an order.
A struct inside a struct
Define the inner structure first, then use it as a member type:
#include <stdio.h>
struct Date {
int day;
int month;
int year;
};
struct Employee {
char name[30];
struct Date birthday;
struct Date hired;
};
int main(void) {
struct Employee e = {
"Kenji Sato",
{14, 2, 1990},
{1, 9, 2018}
};
printf("%s\n", e.name);
printf(" born: %02d.%02d.%d\n", e.birthday.day, e.birthday.month, e.birthday.year);
printf(" hired: %02d.%02d.%d\n", e.hired.day, e.hired.month, e.hired.year);
return 0;
}Kenji Sato
born: 14.02.1990
hired: 01.09.2018
To reach an inner member, chain the dot operators from the outside in: e.birthday.year means "the year of the birthday of e".
Nested braces in the initialiser mirror the nesting of the types. Designated initialisers work at every level, which makes larger initialisations much easier to read:
struct Employee e = {
.name = "Kenji Sato",
.birthday = {.day = 14, .month = 2, .year = 1990},
.hired = {.day = 1, .month = 9, .year = 2018},
};Reusing the inner type
Because struct Date is an ordinary type, you can write functions for it once and use them for every date in every structure:
#include <stdio.h>
struct Date {
int day, month, year;
};
struct Order {
int id;
struct Date placed;
struct Date shipped;
double total;
};
void print_date(struct Date d) {
printf("%04d-%02d-%02d", d.year, d.month, d.day);
}
int date_before(struct Date a, struct Date b) {
if (a.year != b.year) return a.year < b.year;
if (a.month != b.month) return a.month < b.month;
return a.day < b.day;
}
int main(void) {
struct Order o = {501, {28, 11, 2024}, {2, 12, 2024}, 79.90};
printf("Order %d placed ", o.id);
print_date(o.placed);
printf(", shipped ");
print_date(o.shipped);
printf("\nShipped after placing? %s\n", date_before(o.placed, o.shipped) ? "yes" : "no");
o.shipped.day = 3; // modify a nested member
printf("Corrected ship date: ");
print_date(o.shipped);
printf("\n");
return 0;
}Order 501 placed 2024-11-28, shipped 2024-12-02
Shipped after placing? yes
Corrected ship date: 2024-12-03
Pointers and nested members
With a pointer to the outer structure, use -> for the first step and . for the members of the embedded struct (which is not a pointer):
#include <stdio.h>
struct Vec2 {
double x, y;
};
struct Body {
const char *name;
struct Vec2 position;
struct Vec2 velocity;
};
void step(struct Body *b, double dt) {
b->position.x += b->velocity.x * dt;
b->position.y += b->velocity.y * dt;
}
int main(void) {
struct Body ball = {"ball", {0.0, 10.0}, {2.0, -1.5}};
for (int t = 1; t <= 3; t++) {
step(&ball, 1.0);
printf("t=%d %s at (%.1f, %.1f)\n", t, ball.name, ball.position.x, ball.position.y);
}
return 0;
}t=1 ball at (2.0, 8.5)
t=2 ball at (4.0, 7.0)
t=3 ball at (6.0, 5.5)
Nesting arrays and structs
Members can be arrays of structs, and structs can contain arrays. Combining them models quite complex data:
#include <stdio.h>
struct Address {
char street[40];
char city[20];
};
struct Contact {
char name[20];
struct Address home;
char phones[2][16];
};
struct AddressBook {
int count;
struct Contact entries[3];
};
int main(void) {
struct AddressBook book = {
2,
{
{"Olga", {"12 Elm Road", "Leeds"}, {"0113 555 0101", "07700 900123"}},
{"Pavel", {"8 Quay Street", "Cork"}, {"021 555 0199", ""}},
}
};
for (int i = 0; i < book.count; i++) {
const struct Contact *c = &book.entries[i];
printf("%s, %s, %s\n", c->name, c->home.street, c->home.city);
for (int p = 0; p < 2; p++) {
if (c->phones[p][0] != '\0') {
printf(" phone: %s\n", c->phones[p]);
}
}
}
return 0;
}Olga, 12 Elm Road, Leeds
phone: 0113 555 0101
phone: 07700 900123
Pavel, 8 Quay Street, Cork
phone: 021 555 0199
Reading c->home.city aloud helps: "the city of the home of the contact c points to".
Embedding vs. pointing
| Approach | Example member | Meaning |
|---|---|---|
| Embedded struct | struct Date hired; |
the date is stored inside the employee; copying the employee copies the date |
| Pointer to struct | struct Department *dept; |
the employee refers to a department stored elsewhere; many employees can share it |
A struct cannot contain a member of its own type (it would be infinitely large), but it can contain a pointer to its own type. That is how linked lists and trees are built:
struct Node {
int value;
struct Node *next; // fine: just an address
};Tip: If you find yourself writing
a.b.c.d.e, the design may be too deeply nested. Helper functions that take the inner struct (likeprint_date) keep the code readable.
Test yourself
Given struct Employee e; with a member struct Date hired;, how do you access the year?
- e.year
- e->hired->year
- e.hired.year
- hired.e.year
If p is a struct Body * and position is an embedded struct member, which expression is correct?
- p.position.x
- p->position.x
- p->position->x
- *p.position.x
Why can a struct contain struct Node *next; but not struct Node next;?
- Pointers are faster
- A struct containing itself would have infinite size; a pointer has a fixed size
- It is just a naming rule
- Both are allowed