Nested Structures in C
In the previous lesson, you learned how to group related data using structures.
Now we take the next natural step: a structure inside another structure.
This concept is called nested structures.
Why Do We Need Nested Structures?
Real-world data is often layered.
For example, consider a student:
- Personal details
- Academic details
- Contact details
Keeping everything flat becomes confusing. Nested structures help organize data logically.
What Is a Nested Structure?
A nested structure is simply:
A structure that contains another structure as a member.
This allows complex data to be represented cleanly.
Defining Nested Structures
First, define the inner structure:
struct Date {
int day;
int month;
int year;
};
Now, include it inside another structure:
struct Student {
int roll;
char name[20];
struct Date dob;
};
Creating and Accessing Nested Structure Members
Use the dot operator repeatedly:
struct Student s1;
s1.roll = 101;
strcpy(s1.name, "Ravi");
s1.dob.day = 15;
s1.dob.month = 8;
s1.dob.year = 2002;
Each dot moves one level deeper.
Complete Example Program
#include <stdio.h>
#include <string.h>
struct Date {
int day;
int month;
int year;
};
struct Student {
int roll;
char name[20];
struct Date dob;
};
int main() {
struct Student s1;
s1.roll = 1;
strcpy(s1.name, "Anjali");
s1.dob.day = 10;
s1.dob.month = 12;
s1.dob.year = 2001;
printf("Roll: %d\n", s1.roll);
printf("Name: %s\n", s1.name);
printf("DOB: %d-%d-%d\n",
s1.dob.day,
s1.dob.month,
s1.dob.year);
return 0;
}
Memory Understanding
All members of nested structures are stored together in memory.
The inner structure does not live separately — it becomes part of the outer structure.
You can check total size using:
printf("%lu", sizeof(struct Student));
Real-World Analogy
Think of a folder:
- Student Folder
- Inside it → Personal Info Folder
- Inside that → Date of Birth
Nested structures organize data the same way.
Where Nested Structures Are Used
- Employee records
- Banking systems
- File headers
- Operating system structures
Mini Practice
- Create a structure
Address(city, pincode) - Embed it inside a structure
Employee - Store and display values
Quick Quiz
Q1. What is a nested structure?
A structure inside another structure.
Q2. How do you access inner structure members?
Using multiple dot operators.
Q3. Does nested structure occupy separate memory?
No, it becomes part of the outer structure.
Q4. Are nested structures used in real applications?
Yes, very commonly.
Q5. Can nesting go more than one level deep?
Yes.