Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

What is Nested Structure in C

Last Updated on January 17, 2024 by Ankit Kochar

Nested structures in the C programming language provide a powerful mechanism to organize and represent complex data. While a structure allows you to group related variables under a single name, nesting structures enables you to create more intricate and hierarchical data structures. This article delves into the concept of nested structures in C, exploring their syntax, advantages, and common use cases. Whether you’re a beginner or an experienced programmer, understanding nested structures can significantly enhance your ability to model real-world scenarios in your C programs.

What is Structure in C Programming Language?

In C, The structure is a user-defined data type that is used to store a group of items of different data types as a single data type. Each element of a structure is known as its member.

Syntax of Structure in C

The syntax of structure in C language:

    struct struct_Name
{
    // Members of the structure 
            int studentId;
        float marks;
};

Suppose we have an entity ‘Student’, and we need the name and student id of each student. Instead of storing all the names and ids of each student in some array or vector, we can create a structure ‘Student’ in the following manner:

Example of Structure in C

A simple example of structure in C language is discussed below:

struct Student
{
                char name[30];
                int studentId;
};

Now, We have a brief understanding of Structure in C.

What is Nested Structure in C?

In C, a structure is defined using the struct keyword, followed by the structure name, and then the structure members enclosed within curly braces.

Syntax of Nested Structure in C

Below is the syntax of nested structure in C language:

struct outer_struct {
   // outer structure members
   int outer_member1;
   float outer_member2;

   // nested structure definition
   struct inner_struct {
      // inner structure members
      int inner_member1;
      float inner_member2;
   } inner;
};

Example of Nested Structure in C

struct school{
   int numberOfStudents;
   int numberOfTeachers;
    struct student{
        char name[50];
        int class;
        int roll_Number;
    } std;
};

Explanation:
In the above example of nested structure in C, there are two structures Student (depended structure) and another structure called School(Outer structure). The structure School has the data members like numberOfStudents, numberOfTeachers, etc. and the Student structure is nested inside the structure School and it has the data members like name, class, roll_Number, etc.

To access the members of the school structure, you use dot notation. For example, to access the numberOfStudents member of the school structure, you would use the following syntax:

struct school s;
s.numberOfStudents = 100;

To access the members of the nested student structure, you would use the following syntax:

strcpy(s.std.name, "John Smith");
s.std.class = 10;
s.std.roll_Number = 1;

Note that the dot notation is used to access the members of the std structure, which is a member of the school structure.
The nested structure student contains three members: name, class, and roll_Number. This structure can be useful in situations where you need to store information about a student, such as their name, class, and roll number.

Ways in Which a Structure Can Be Nested

The structure can be nested in the following different ways:

  1. By Separate Nested Structure
  2. By Embedded Nested Structure.
  • By Separate Nested Structure: In this method, the two structures are created, but the dependent structure(Employee) should be used inside the main structure(Organisation) as a member. For a better understanding let’s see an example of separate nested structure in c language.

    C Program implemented by Separate Nested Structure

    #include <stdio.h>
    struct employee{
        char name[50];
        int id;
        int age;
    };
    
    
    struct organisation{
        char name[50];
        int id;
        struct employee emp;
    };
    
    
    int main(){
        struct organisation org1 = {"XYZ Ltd.", 123, {"John Doe", 101, 30}};
        printf("Organisation name: %s\n", org1.name);
        printf("Organisation ID: %d\n", org1.id);
        printf("Employee name: %s\n", org1.emp.name);
        printf("Employee ID: %d\n", org1.emp.id);
        printf("Employee age: %d\n", org1.emp.age);
        return 0;
    }

    Output

    Organisation name: XYZ Ltd.
    Organisation ID: 123
    Employee name: John Doe
    Employee ID: 101
    Employee age: 30

    In this approach, the employee structure is declared separately from the organisation structure. Then, a member of the employee structure is included in the organisation structure as struct employee emp. In the main function, we create an instance of the organisation structure and initialize the emp member with an instance of the employee structure.

  • By Embedded Nested Structure: In this method, the two structures are combined into one structure. For a better understanding let’s see an example of embedded nested structure in c language.

    C Program implemented by Embedded Nested Structure

    #include <stdio.h>
    struct organisation{
        char name[50];
        int id;
        struct {
            char name[50];
            int id;
            int age;
        } emp;
    };
    
    int main(){
        struct organisation org1 = {"XYZ Ltd.", 123, {"John Doe", 101, 30}};
        printf("Organisation name: %s\n", org1.name);
        printf("Organisation ID: %d\n", org1.id);
        printf("Employee name: %s\n", org1.emp.name);
        printf("Employee ID: %d\n", org1.emp.id);
        printf("Employee age: %d\n", org1.emp.age);
        return 0;
    }

    Output

    Organisation name: XYZ Ltd.
    Organisation ID: 123
    Employee name: John Doe
    Employee ID: 101
    Employee age: 30

    In this approach, the employee structure is declared inside the organization structure as an anonymous structure using the keyword struct. In the main function, we create an instance of the organization structure and initialize the emp member directly with the values of the employee structure.

Accessing Nested Structure

Nested Structure can be accessed in two ways:

  1. Using Normal Vriable.
  2. Using Pointer Variable.
  • Using Normal Variable: Outer and inner structure variables are declared as normal variables and the data members of the outer structure are accessed using a single dot(.) and the data members of the inner structure are accessed using the two dots. We have already used this method in this article.
  • Using Pointer Variable: A nested structure can be accessed using a pointer variable by using a combination of dot (.) and arrow (->) operators to access the data members.

    Here is an example program to illustrate how to access a nested structure using a pointer variable:

    #include <stdio.h>
    
    // Declare a nested structure
    struct employee {
        char name[20];
        int age;
        struct address {
            char city[20];
            char state[20];
        } addr;
    };
    
    int main() {
        // Declare a pointer variable of the structure
        struct employee *emp_ptr;
    
        // Declare and initialize a normal variable of the structure
        struct employee emp = {"John", 25, {"New York", "NY"}};
    
        // Assign the address of the normal variable to the pointer variable
        emp_ptr = &emp;
    
        // Access the data members of the outer structure using arrow operator
        printf("Name: %s\n", emp_ptr->name);
        printf("Age: %d\n", emp_ptr->age);
    
        // Access the data members of the inner structure using dot and arrow operators
        printf("City: %s\n", emp_ptr->addr.city);
        printf("State: %s\n", emp_ptr->addr.state);
    
        return 0;
    }

    Output

    Name: John
    Age: 25
    City: New York
    State: NY

Passing Structure to Function

We can pass Nested structures to functions directly by passing the structure as an argument to the function.

Code

#include <stdio.h>

struct Inner {
    int x;
};

struct Outer {
    int a;
    int b;
    struct Inner in;
};

void show(struct Outer out) {
    printf("a = %d\n", out.a);
    printf("b = %d\n", out.b);
    printf("x = %d\n", out.in.x);
}

int main() {
    struct Outer out = {1, 2, {3}};
    show(out);
    return 0;
}

Output

a = 1
b = 2
x = 3

In this example, there are two C structs Inner and Outer, where Outer contains an instance of Inner. The show function takes an instance of Outer and prints its a, b, and x values. In main, an instance of Outer is created and initialized with values 1 for a, 2 for b, and 3 for x. Then, this instance is passed as an argument to the show function. When the program is run, it prints the values of a, b, and x in the show function, which are 1, 2, and 3, respectively.

Drawbacks of Nested Structure

The drawback of nested structures are:

  • Independent existence not possible: Nested structures cannot exist independently and cannot be declared as a structure variable of its own type anywhere else in the program. This means that they are limited in their use and cannot be used outside of the main structure.
  • Cannot be used in multiple data structures: Nested structures cannot be used in multiple structures due to the limitation of declaring structure variables within the main structure. This can limit the flexibility and reusability of the code.

In this program, we have declared a nested structure employee that contains an inner structure address. We have then declared a pointer variable emp_ptr of the structure and a normal variable emp of the structure, and assigned the address of emp to emp_ptr.

To access the data members of the outer structure, we have used the arrow (->) operator with the pointer variable emp_ptr. To access the data members of the inner structure, we have used the dot (.) operator to access the addr member of the outer structure, and the arrow (->) operator to access the data members of the inner structure.

Overall, nested structures in C provide a powerful way to group related data together in a hierarchical manner. By understanding how to define and access nested structures, you can write more efficient and effective C code.

Conclusion
In conclusion, nested structures in C offer a robust means of organizing and representing complex data relationships. By allowing structures to be defined within other structures, C programmers can create hierarchical data structures that mirror the intricacies of real-world scenarios. As you explore the nuances of nested structures, you’ll find that this feature greatly enhances code clarity, organization, and the ability to model diverse data structures efficiently. Mastering nested structures is a valuable skill that contributes to writing more maintainable and expressive C code.

FAQs related to Nested Structure in C

Here are some FAQs related to Nested Structure in C.

1. What is the advantage of using nested structures?
Nested structures provide a way to represent complex relationships between data elements more intuitively. They enhance code organization and readability by grouping related information within a structured hierarchy.

2. Can a nested structure have multiple levels of nesting?
Yes, a nested structure can have multiple levels of nesting. You can define structures inside structures, and those inner structures can themselves contain further structures.

3. How do you access members of nested structures?
To access members of nested structures, you use the dot operator repeatedly. For example, if you have a nested structure OuterStruct containing InnerStruct, you would access a member of InnerStruct like this: outer.inner.member.

4. Are there any limitations to nested structures in C?
While nested structures offer flexibility, excessive nesting may lead to code complexity. It’s essential to strike a balance between structure depth and code maintainability.

5. Can nested structures be used with arrays in C?
Yes, nested structures can be used with arrays. You can declare arrays of structures and nest those arrays within other structures to create multidimensional data structures.

6. What is the difference between nested structures and arrays of structures?
Nested structures involve defining one structure within another, providing a hierarchical organization. Arrays of structures, on the other hand, involve creating an array where each element is a structure. They serve different purposes based on data organization needs.

7. How does memory allocation work for nested structures?
Memory is allocated consecutively for the members of a structure, including nested structures. The memory layout is determined by the order of declaration in the structure definition.

8. In what scenarios is the use of nested structures beneficial?
Nested structures are beneficial in scenarios where data has a hierarchical relationship. Examples include representing a university with departments and students, or a company with divisions and employees. They provide a natural way to model complex real-world entities.

Leave a Reply

Your email address will not be published. Required fields are marked *