← Back to C Course | Chapter 8: Structures & Unions | Lesson 2 of 7

C Nested Structures

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?

c
#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;
}

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

c
#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;
}

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

c
#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;
}

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

c
#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;
}

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

c
#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;
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.