Nearby lessons

104 of 124

C - Nested Structures

Nested Structures is one of the foundational topics in C programming. This lesson explains Program 5: Nested Structures with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Program 5: Nested Structures

A structure can contain another structure. For example, a Student can contain an Address:

Example01
CCode Cell
1#include <stdio.h>
2#include <string.h>
3 
4struct address {
5 char city[30];
6 int pin;
7};
8 
9struct student {
10 int rollNo;
11 struct address addr; // structure inside a structure
12};
13 
14void main()
15{
16 struct student s;
17 
18 s.rollNo = 101;
19 strcpy(s.addr.city, "Hyderabad"); // reach through both levels
20 s.addr.pin = 500038;
21 
22 printf("Roll: %d\n", s.rollNo);
23 printf("City: %s\n", s.addr.city);
24 printf("Pin : %d\n", s.addr.pin);
25}
Output
Roll: 101 City: Hyderabad Pin : 500038
📝 Key Takeaways
  • Structure groups different types under one name — like a form.
  • Define the template, declare variables, access members with the dot.
  • Separate programs: access, one-line init, user input, arrays of structures.
  • Structures can nest inside structures.
  • Union shares one memory for all members; structure gives each member its own.
  • sizeof(union) = largest member; sizeof(struct) = sum of members.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1