Defining a struct inside another struct
What you'll learn: How to organize complex data by nesting one structure definition inside another to create a clear hierarchy.
The Russian Doll approach
In C, a struct is a way to group related variables. However, as your programs grow, a single flat list of variables can become messy. Imagine you are building a system for a library. You could put the author's name, birth year, and nationality all directly inside a Book struct. But it makes more sense to group those "author-specific" details into their own category.
Nesting a struct is like placing a smaller box inside a larger box. It allows you to create a logical hierarchy, making your code easier to read and maintain. Instead of a disorganized pile of data, you create a structured map.
How to nest structures
You can define a structure within the curly braces of another structure. Once defined, you can immediately declare a variable of that type to be used as a member.
In the example below, we define an Address structure directly inside a User structure. Notice how we then access the data using the "dot" operator twice—once to get into the user, and again to get into the address.
#include <stdio.h>
struct User {
char username[50];
// Nested structure definition
struct Address {
char street[100];
char city[50];
int zipCode;
} homeAddress; // We define the type and create a member named 'homeAddress'
};
int main() {
struct User employee;
// Accessing nested members using two dots
employee.homeAddress.zipCode = 90210;
printf("The zip code is: %d\n", employee.homeAddress.zipCode);
return 0;
}
Why do this?
By nesting the Address inside the User, you tell the compiler (and other programmers) that this specific address format is intrinsically tied to the user. It prevents "namespace pollution," where you might accidentally mix up a zipCode variable for a user with a zipCode variable for a shipping warehouse.
It also makes your code "self-documenting." When you type employee.homeAddress.city, the path to the data is perfectly clear, following a logical flow from the container to the specific detail.
Key takeaway
Nest structures to group related data hierarchically, using multiple dots (e.g., parent.child.member) to access the inner values.