Table of contents
1.
Introduction
2.
Syntax of Nested Structures in C
3.
Example of Nested Structure in C
3.1.
C
4.
Different Ways of Nesting Structures in C
4.1.
By Separate Nested Structure
4.2.
By Embedded Nested Structure
5.
Drawbacks of Nested Structures in C
6.
C Nested Structure Example
6.1.
C
7.
Passing Nested Structures to Functions in C
7.1.
Pass the Nested Structure Variable at Once
7.2.
C
7.3.
Pass the Nested Structure Members as an Argument into the Function
7.4.
C
7.5.
Accessing Nested Structures in C
7.6.
Using Normal Variable
7.7.
C
7.8.
Using Pointer Variable
7.9.
C
8.
Frequently Asked Questions
8.1.
What is a nested structure in C?
8.2.
What is nested if structure in C?
8.3.
What is nested for in C?
9.
Conclusion
Last Updated: Nov 20, 2024
Medium

Nested Structure in C

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Nested structures in C allow you to create complex data types by combining different structures within each other. This powerful feature enables you to organize and group related data members efficiently. Nested structures provide a way to represent hierarchical relationships and create more meaningful abstractions in your programs. 

Nested Structure in C

In this article, we will learn about the syntax of nested structures, look at examples of how they can be defined and used, and discuss different ways of working with nested structures effectively.

Syntax of Nested Structures in C

In C programming, a nested structure is defined by declaring one structure inside another. 

Here is how you can define a basic nested structure:

struct Address {
    int houseNumber;
    char streetName[50];
};
struct Person {
    char name[50];
    struct Address address;
};


In this example, we have two structures: Address and Person. The Person structure includes name as a character array and address as an instance of the Address structure. This allows us to store both personal and address details for a person within a single structure.

To create & initialize an instance of a nested structure, you can use the following code:

struct Person person1 = {
    "Cristiano Ronaldo",
    {123, "Baker Street"}
};


Here, person1 is an instance of the Person structure. We directly provide values for the name and address details in the declaration. This simple syntax makes it easy to handle related data effectively.

Example of Nested Structure in C

In this example, we'll fill out a person's information and print it.

  • C

C

#include <stdio.h>
#include<string.h>
struct Address {
int houseNumber;
char streetName[50];
};

struct Person {
char name[50];
struct Address address;
};

int main() {
struct Person person1;

// Assigning data to person1
strcpy(person1.name, "Cristiano Ronaldo");
person1.address.houseNumber = 123;
strcpy(person1.address.streetName, "Baker Street");

// Printing the data
printf("Name: %s\n", person1.name);
printf("Address: %d, %s\n", person1.address.houseNumber, person1.address.streetName);

return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

Name: Cristiano Ronaldo
Address: 123, Baker Street


In this code:

  • We use strcpy from the <string.h> library to copy strings into the character arrays.
     
  • We access the nested Address structure through the Person structure to set and retrieve the house number and street name.
     
  • Finally, we print the details of person1 to show how the data is organized and accessed.

Different Ways of Nesting Structures in C

When working with nested structures in C, there are two primary methods you can choose from: separate nesting and embedded nesting. Each method has its applications depending on the complexity of the data and the level of encapsulation you need.

By Separate Nested Structure

Separate nesting involves defining each structure independently and then using one structure as a member of another. This method is useful when the nested structure is also needed separately elsewhere in your program. For example:

struct Date {
    int day;
    int month;
    int year;
};
struct Event {
    char eventName[100];
    struct Date eventDate;
};


Here, the Date structure can be used in multiple other structures, such as Event, Appointment, or Reminder.

By Embedded Nested Structure

Embedded nesting means defining one structure completely within another. This method is ideal when a nested structure is only relevant within the context of the enclosing structure and not used independently. For example:

struct Car {
    char make[50];
    char model[50];
    struct {
        char engineType[50];
        int engineCapacity;
    } engine;
};


In this example, the engine structure is defined within the Car structure, making the engine details an integral part of the Car and not relevant outside of it.

Drawbacks of Nested Structures in C

  • Complexity in Accessing Data: The deeper the nesting, the more complex the code becomes for accessing data fields. Deeply nested structures require multiple dot operators (.) or arrow operators (->) for pointer variables, which can make the code harder to read and maintain.
     
  • Memory Overhead: Nested structures might cause more memory consumption than necessary, especially if not all the data fields in the nested structures are used. This is because the entire nested structure needs to be allocated memory, even if only a part of it is used.
     
  • Difficulty in Initialization: Initializing nested structures can become cumbersome as the level of nesting increases. The initialization code can become lengthy and prone to errors, especially when multiple levels of structures are involved.
     
  • Code Maintenance: Changes in the structure might require updates across various parts of the program where the nested structure is used. This can increase the maintenance overhead and the potential for introducing bugs during updates.


Despite these challenges, nested structures are still highly valuable for certain applications where the advantages of structured data organization outweigh the drawbacks.

C Nested Structure Example

In this example, we'll create a structure for a university system that involves a structure for a student and a nested structure for the student's course information.

  • C

C

#include <stdio.h>
#include <string.h>

struct Course {
char courseName[50];
int credits;
};

struct Student {
char name[50];
int age;
struct Course course;
};

int main() {
struct Student student1;

// Assigning student information
strcpy(student1.name, "Luka Modric");
student1.age = 20;

// Assigning course information to the student
strcpy(student1.course.courseName, "Computer Science");
student1.course.credits = 3;

// Printing the student's information
printf("Student Name: %s\n", student1.name);
printf("Age: %d\n", student1.age);
printf("Course Name: %s\n", student1.course.courseName);
printf("Credits: %d\n", student1.course.credits);

return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

Student Name: Luka Modric
Age: 20
Course Name: Computer Science
Credits: 3


In this code:

  • We define two structures: Course and Student. Course is nested within Student.
     
  • We use the strcpy function to assign string values to the character arrays.
     
  • The Student structure includes personal details and course details, allowing us to store and manage related information efficiently.

Passing Nested Structures to Functions in C

Passing nested structures to functions in C can be done in several ways, each serving different needs. We'll explore two main methods: passing the entire nested structure at once, and passing individual members of a nested structure as arguments.

Pass the Nested Structure Variable at Once

This method involves passing the entire structure to a function. This is straightforward and ensures that all the data contained within the structure is available to the function. Here's how you can do it:

  • C

C

#include <stdio.h>

struct Inner {
int x;
};

struct Outer {
int y;
struct Inner inner;
};

void displayStructure(struct Outer o) {
printf("Outer y: %d\n", o.y);
printf("Inner x: %d\n", o.inner.x);
}

int main() {
struct Outer out;
out.y = 5;
out.inner.x = 10;

displayStructure(out); // Passing the whole structure
return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

Outer y: 5
Inner x: 10


In this example, the displayStructure function receives a complete Outer structure and prints both its own value and the value of the nested Inner structure.

Pass the Nested Structure Members as an Argument into the Function

Sometimes, you may only need to work with specific parts of a nested structure within a function. In such cases, you can pass individual members instead of the whole structure:

  • C

C

#include <stdio.h>

struct Inner {
int x;
};

struct Outer {
int y;
struct Inner inner;
};

void displayInner(struct Inner in) {
printf("Inner x: %d\n", in.x);
}

int main() {
struct Outer out;
out.y = 5;
out.inner.x = 10;

displayInner(out.inner); // Passing only the nested member
return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

Inner x: 10


Here, displayInner only needs data from the Inner structure, so we pass just that part from the Outer structure. This method can be more efficient when the function does not require the entire outer structure.

Both methods of passing nested structures to functions can be useful depending on what part of the data the function needs to access. Choosing the right method helps keep your programs efficient and clear.

Accessing Nested Structures in C

Accessing data within nested structures in C can be done in two primary ways: using normal variables and using pointer variables. Understanding these methods is crucial for effectively managing and utilizing nested structures in your programs.

Using Normal Variable

When you're not dealing with pointers, you access nested structure members using the dot operator (.). This is straightforward when you have a simple structure or when you have nested structures within a function. Here’s how you do it:

  • C

C

#include <stdio.h>
struct Date {
int day;
int month;
int year;
};

struct Identity {
char name[100];
struct Date birthdate;
};
int main() {
struct Identity id;

id.name[0] = 'J';
id.name[1] = 'o';
id.name[2] = 'h';
id.name[3] = 'n';
id.name[4] = '\0';

id.birthdate.day = 15;
id.birthdate.month = 6;
id.birthdate.year = 1992;
printf("Name: %s\n", id.name);
printf("Birthdate: %02d/%02d/%d\n", id.birthdate.day, id.birthdate.month, id.birthdate.year);

return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

Name: Jude
Birthdate: 15/06/1992


In this example, Identity has a nested Date structure. We access each field using the dot operator to set and retrieve data.

Using Pointer Variable

When dealing with pointers to structures, you use the arrow operator (->) to access members. This is common in dynamic memory situations, such as when structures are allocated memory using functions like malloc. Here's an example:

  • C

C

#include <stdio.h>
#include <stdlib.h>
struct Date {
int day;
int month;
int year;
};
struct Identity {
char name[100];
struct Date *birthdate;
};
int main() {
struct Identity *id = malloc(sizeof(struct Identity));
id->birthdate = malloc(sizeof(struct Date));
strcpy(id->name, "Jude");
id->birthdate->day = 15;
id->birthdate->month = 6;
id->birthdate->year = 1992;
printf("Name: %s\n", id->name);
printf("Birthdate: %02d/%02d/%d\n", id->birthdate->day, id->birthdate->month, id->birthdate->year);

free(id->birthdate);
free(id);

return 0;
}
You can also try this code with Online C Compiler
Run Code

Output

Name: Jude
Birthdate: 15/06/1992


In this example, both Identity and Date are accessed through pointers. We use the arrow operator to access and modify the data efficiently.

Frequently Asked Questions

What is a nested structure in C?

A nested structure in C is a structure that contains another structure as a member, allowing the creation of complex data types.

What is nested if structure in C?

A nested if structure in C refers to an if statement inside another if statement, allowing for multiple conditions to be checked sequentially.

What is nested for in C?

A nested for loop in C is a for loop inside another for loop, allowing for iteration over multi-dimensional data or performing repeated tasks.

Conclusion

In this article, we have learned about nested structures in C, including their syntax, practical examples, different ways of nesting, drawbacks, and methods for passing and accessing these structures in functions. Nested structures are a powerful tool for organizing complex data, but they require careful handling to maintain efficiency and readability in your code. 

You can refer to our guided paths on Code360. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass