C Nested Structures – Embedding Structures in Structures
In C, you can define a structure inside another structure — this is called a nested structure. It’s useful when you want to group related data within a bigger structure.
🔹 What is a Nested Structure?
A nested structure means putting one structure as a member of another. It helps organize complex data more logically.
📝 Example: C Nested Structure
In this example, we create a Student
structure that contains an Address
structure inside it.
#include <stdio.h> struct Address { char city[20]; int pincode; }; struct Student { char name[30]; int roll; struct Address addr; }; int main() { struct Student stu; // Assigning values strcpy(stu.name, "Ravi"); stu.roll = 101; strcpy(stu.addr.city, "Delhi"); stu.addr.pincode = 110001; // Displaying values printf("Name: %s\n", stu.name); printf("Roll No: %d\n", stu.roll); printf("City: %s\n", stu.addr.city); printf("Pincode: %d\n", stu.addr.pincode); return 0; }
📌 Tip Time
- You can define the nested structure either inside or outside the main structure.
- Access nested members using dot notation like:
outer.inner.member
🎯 Try This Yourself!
Make a structure for Employee with nested Date for joining date and see if you can access the day, month, and year. 💪