Back to: C Tutorials For Beginners and Professionals
Nested Structure in C Language with Examples
In this article, I will discuss the Nested Structure in C Language with Examples. Please read our previous article discussing Self-Referential Structure in C Language with Examples. At the end of this article, you will understand the following pointers:
- What is Nested Structure in C Language?
- Nested Structure Example in C Language
- Real-Time Examples: Student Information System, Employee and Address Information, Computer Hardware Specifications
- When to Use Nested Structure in C?
What is Nested Structure in C Language?
In C programming, a nested structure is a structure within another structure. This allows you to create more complex data types that are organized in a hierarchical manner. Here’s a basic overview of how you can use nested structures in C:
Define the Inner Structure:
First, you define a basic structure that will be used within another structure.
struct Date { int day; int month; int year; };
Define the Outer Structure:
Next, you define the outer structure, including the inner structure as a member.
struct Employee { char name[50]; int id; struct Date birthday; // Nested structure };
Initializing Nested Structures
You can initialize nested structures the same way you initialize regular structures, but you also need to provide values for the nested elements.
struct Employee emp = {"Krish", 101, {10, 11, 2014}};
Accessing Members of Nested Structures
To access the members of a nested structure, you use the dot operator (.) multiple times, traversing through the layers of the structure.
printf("Employee ID: %d\n", emp.id); printf("Birthday: %d-%d-%d\n", emp.birthday.day, emp.birthday.month, emp.birthday.year);
Nested Structure in C Language
When working with a nested structure, the size of the structure is the sum of inner structure properties, and outer structure properties are to be calculated. When working with a nested structure, it is impossible to access inner structure members directly by using the outer structure variable. We must create an inner structure variable to access inner structure members using the outer structure variable within the body only. The inner structure variable cannot access outer structure members directly or indirectly. Structures can be nested within other structures in C programming.
#include <stdio.h> #include <string.h> struct Employee { int id; char name[20]; struct Date { int dd; int mm; int yyyy; } doj; } e1; int main () { //storing employee information e1.id = 101; strcpy (e1.name, "Krish"); //copying string into char array e1.doj.dd = 10; e1.doj.mm = 11; e1.doj.yyyy = 2014; //printing first employee information printf ("employee id : %d\n", e1.id); printf ("employee name : %s\n", e1.name); printf ("employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd, e1.doj.mm, e1.doj.yyyy); return 0; }
Output:
Usage Example:
Nested structures are particularly useful in scenarios where you have hierarchical data. For instance, if you represent an organization where each employee has a date of birth, address, and other complex attributes, nested structures can help organize this data efficiently.
Points to Remember
- Initialization of nested structures can be tricky, so pay attention to the syntax.
- You need to use the dot operator for each nesting level when accessing nested structure members.
- Nested structures can significantly increase your programs’ readability and manageability of complex data types.
Nested Structure Real-Time Examples in C Language
Nested structures in C are a way to create complex data types by placing one structure within another. This approach is useful when dealing with data that is naturally hierarchical or has several layers of complexity. Let’s go through some examples to understand how nested structures work in C.
Example: Student Information System
In this example, we’ll create a structure for a student that includes another structure for the student’s date of birth.
#include <stdio.h> // Structure for Date struct Date { int day; int month; int year; }; // Structure for Student, which includes a Date structure struct Student { char name[50]; struct Date dob; // Nested structure float gpa; }; int main() { struct Student student1; // Assigning values to student1 strcpy(student1.name, "Alice"); student1.dob.day = 1; student1.dob.month = 1; student1.dob.year = 2000; student1.gpa = 3.5; // Printing student details printf("Name: %s\n", student1.name); printf("Date of Birth: %02d/%02d/%04d\n", student1.dob.day, student1.dob.month, student1.dob.year); printf("GPA: %.2f\n", student1.gpa); return 0; }
Example: Employee and Address Information
Here, we’ll define an employee structure that includes an address structure.
#include <stdio.h> // Structure for Address struct Address { char street[100]; char city[50]; char state[50]; int zip; }; // Structure for Employee, which includes an Address structure struct Employee { char name[50]; struct Address address; // Nested structure float salary; }; int main() { struct Employee emp1; // Assigning values to emp1 strcpy(emp1.name, "Bob"); strcpy(emp1.address.street, "1234 Maple Street"); strcpy(emp1.address.city, "Metropolis"); strcpy(emp1.address.state, "NY"); emp1.address.zip = 12345; emp1.salary = 50000.00; // Printing employee details printf("Name: %s\n", emp1.name); printf("Address: %s, %s, %s, %d\n", emp1.address.street, emp1.address.city, emp1.address.state, emp1.address.zip); printf("Salary: %.2f\n", emp1.salary); return 0; }
Example 3: Computer Hardware Specifications
This example illustrates nested structures to represent computer hardware specifications.
#include <stdio.h> // Structure for Processor struct Processor { char brand[50]; float speedGHz; }; // Structure for Computer, including Processor and Memory struct Computer { struct Processor cpu; // Nested structure int ramGB; int storageGB; }; int main() { struct Computer myComputer; // Assigning values strcpy(myComputer.cpu.brand, "Intel"); myComputer.cpu.speedGHz = 3.5; myComputer.ramGB = 16; myComputer.storageGB = 512; // Printing computer specifications printf("CPU: %s, %.2fGHz\n", myComputer.cpu.brand, myComputer.cpu.speedGHz); printf("RAM: %dGB\n", myComputer.ramGB); printf("Storage: %dGB\n", myComputer.storageGB); return 0; }
When to Use Nested Structure in C?
Using nested structures in C is particularly beneficial when dealing with complex data with a hierarchical or layered nature. Here are some scenarios and considerations that indicate when to use nested structures:
- Hierarchical Data Representation: Nested structures are ideal when your data can be naturally divided into subcategories or hierarchies. For example, an Employee structure might contain a Date structure for the birth date and an Address structure for home address details.
- Organizing Complex Data: Nested structures are useful for organizing complex data into more manageable parts. This can simplify code and make it more readable, especially when dealing with large structures.
- Real-world Entities and Relationships: They are excellent for modeling real-world entities and their relationships, where one entity might be part of another. For instance, a Car structure could have a nested Engine structure.
- Reducing Redundancy: If the same subset of data is used in multiple structures, nesting a common structure can reduce redundancy. For example, if multiple structures require address information, you can create a single Address structure and nest it where needed.
- Modular Development: Nested structures can help in modularizing code. Each nested structure can be developed and tested independently and integrated into a larger one.
- Ease of Maintenance: Nested structures can make maintaining and updating the codebase easier. Changes to a specific data type need to be made only in one place rather than in every structure that uses that data.
- Improved Data Handling: When functions need to operate on complex data, passing nested structures can be more efficient and logical. This approach can encapsulate all the relevant data in a single, coherent unit.
- Data Encapsulation: Nested structures are a step towards data encapsulation, a key principle of object-oriented programming. They allow you to bundle data and related sub-data, making your code more organized.
In the next article, I will discuss Structure and Pointer in C Language with Example. In this article, I explain Nested Structure in C Language with Examples. I hope you enjoy this Nested Structure in C Language with Examples article. I would like to have your feedback. Please post feedback, questions, or comments about this article.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.