Nearby lessons

61 of 72

C - Nested Structures

A nested structure means one structure is used as a member inside another structure. For example, a student record can contain an address.

1. Example of a Nested Structure

Here, Address stores a city and a PIN code. The Student structure contains an Address member named address.

Example01
CCode Cell
1#include <stdio.h>
2#include <string.h>
3 
4struct Address {
5 char city[30];
6 int pinCode;
7};
8 
9struct Student {
10 int rollNo;
11 char name[30];
12 struct Address address;
13};
14 
15int main(void) {
16 struct Student s1;
17 
18 s1.rollNo = 101;
19 strcpy(s1.name, "Rahul");
20 strcpy(s1.address.city, "Ahmedabad");
21 s1.address.pinCode = 380001;
22 
23 printf("Roll Number: %d\n", s1.rollNo);
24 printf("Name: %s\n", s1.name);
25 printf("City: %s\n", s1.address.city);
26 printf("PIN Code: %d\n", s1.address.pinCode);
27 
28 return 0;
29}
Output
Roll Number: 101
Name: Rahul
City: Ahmedabad
PIN Code: 380001

2. Understand the Dot Operator

  • s1.name accesses the student's name.
  • s1.address accesses the address structure.
  • s1.address.city accesses the city inside the address.
  • s1.address.pinCode accesses the PIN code inside the address.

Common Mistakes

  • Use the exact member names defined in both structures.
  • Use a dot for each level of a nested structure.
  • Make sure the inner structure type is defined before using it as a member.
📝 Key Takeaways
  • A structure can contain another structure as a member.
  • Use more than one dot to access a nested member.
  • For example, student.address.city accesses the city inside the student address.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1