C Nested Structures
In this page:
What is a Nested Structure?
For example, an Employee structure might contain an Address structure as one of its fields, letting you model has-a relationships between related pieces of data cleanly, similar to composition in object-oriented languages.
Example: What is a Nested Structure?
#include <stdio.h>
struct Address {
char city[20];
};
struct Employee {
char name[20];
struct Address address;
};
int main() {
struct Employee e = {"Alice", {"Springfield"}};
printf("%s %s", e.name, e.address.city);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Defining Nested Structures
The inner structure type must be fully defined (or at least declared) before the outer structure references it, since the compiler needs to know the inner structure's size to correctly lay out the outer structure in memory.
Example: Defining Nested Structures
#include <stdio.h>
struct Address {
char street[30];
};
struct Employee {
char name[20];
struct Address address;
};
int main() {
struct Employee e = {"Bob", {"123 Main St"}};
printf("%s", e.address.street);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Initializing Nested Structures
A nested initializer looks like Employee e = {"Alice", {"123 Main St", "Springfield"}} -- the inner braces group the Address fields separately from the outer Employee fields, mirroring the nesting in the type definition.
Example: Initializing Nested Structures
#include <stdio.h>
struct Address {
char street[30];
char city[20];
};
struct Employee {
char name[20];
struct Address address;
};
int main() {
struct Employee e = {"Alice", {"123 Main St", "Springfield"}};
printf("%s", e.address.city);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Accessing Nested Members
employee.address.city reads the city field by first navigating into the address member, then into its city field -- each dot operator moves one level deeper into the nested structure hierarchy.
Example: Accessing Nested Members
#include <stdio.h>
struct Address {
char city[20];
};
struct Employee {
struct Address address;
};
int main() {
struct Employee employee = {{"Springfield"}};
printf("%s", employee.address.city);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Nesting Arrays of Structures
This lets you model more complex real-world data, like a company with an array of departments, each containing an array of employee structures -- nesting arrays and structures together is how C represents hierarchical data without built-in classes.
Example: Nesting Arrays of Structures
#include <stdio.h>
struct Employee {
char name[20];
};
struct Department {
struct Employee employees[2];
};
int main() {
struct Department d = {{{"Alice"}, {"Bob"}}};
printf("%s %s", d.employees[0].name, d.employees[1].name);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: