In this article, we discuss Nested Structures in C, a method to define a structure within another structure. Nested structures are useful when you want to logically group related data inside a larger structure.
Nested Structure in C Programming
What is Nested Structure in C?
A nested structure is a structure that contains another structure as a member. It allows you to organize complex data efficiently, especially when dealing with hierarchical or grouped data.
For example, if you want to store information about a student along with their address, you can create a structure for the address and nest it inside the student structure.
Syntax of Nested Structure
struct Outer {
int id;
char name[50];
struct Inner {
char street[50];
char city[50];
int zip;
} address;
};
- Outer is the main structure.
- Inner is the nested structure representing the address.
- address is the variable of the nested structure inside Outer.
Example of Nested Structure
#include <stdio.h>
#include <string.h>
struct Address {
char street[50];
char city[50];
int zip;
};
struct Student {
int roll_no;
char name[50];
struct Address addr; // Nested structure
};
int main() {
struct Student s1;
s1.roll_no = 101;
strcpy(s1.name, “Amit”);
strcpy(s1.addr.street, “MG Road”);
strcpy(s1.addr.city, “Pune”);
s1.addr.zip = 411001;
printf(“Student Roll No: %d\n”, s1.roll_no);
printf(“Student Name: %s\n”, s1.name);
printf(“Street: %s\n”, s1.addr.street);
printf(“City: %s\n”, s1.addr.city);
printf(“ZIP Code: %d\n”, s1.addr.zip);
return 0;
}
Output:
Student Roll No: 101
Student Name: Amit
Street: MG Road
City: Pune
ZIP Code: 411001
How to Access Members of Nested Structure
- Use the dot (.) operator to access members of the outer structure.
- Use dot (.) operator again to access members of the nested structure.
Example: s1.addr.city accesses the city member inside the nested Address structure.
Advantages of Nested Structure
- Organizes related data logically.
- Simplifies handling of complex data records.
- Makes code more readable and maintainable.
- Reduces the need for multiple separate structures.
Disadvantages of Nested Structure
- Accessing nested members can be verbose (outer.inner.member).
- Increases memory usage if structures are large.
- Requires careful memory management when used with pointers.
Use Cases of Nested Structures
- Storing student information along with address details.
- Managing employee records with department info.
- Representing hierarchical data like books in a library with publisher details.
Summary
Nested Structures in C allow you to create structured and organized data by embedding one structure inside another. This is useful for real-world applications where a single object has multiple attributes or related sub-objects.
POP- Introduction to Programming Using ‘C’
OOP – Object Oriented Programming
DBMS – Database Management System
RDBMS – Relational Database Management System