Scroll Progress Bar

Nested Structure

In C, a structure inside another structure, this is known as a nested structure. This allows creating more complex data structures by combining multiple data types together.

Usage and Syntax:

To create a nested structure, define a structure inside another structure definition. The inner structure becomes a member of the outer structure, just like any other data type.


struct OuterStruct {
    data_type member1;
    data_type member2;
    // ...
    struct InnerStruct {
        data_type inner_member1;
        data_type inner_member2;
        // ...
    } inner_instance; // Declare an instance of the inner structure
    // ...
} outer_instance; // Declare an instance of the outer structure
Sample Code with Explanation and Output:

#include <stdio.h>

// Define an inner structure
struct Address {
    char city[30];
    char street[50];
    int zip_code;
};

// Define an outer structure containing the inner structure
struct Employee {
    int emp_id;
    char emp_name[50];
    struct Address emp_address; // Nested structure as a member
};

int main() {
    // Declare and initialize an instance of the outer structure
    struct Employee emp1 = {
        .emp_id = 101,
        .emp_name = "John Doe",
        .emp_address = {
            .city = "New York",
            .street = "Main Street",
            .zip_code = 10001
        }
    };

    // Access and print the information using nested structures
    printf("Employee ID: %d\n", emp1.emp_id);
    printf("Employee Name: %s\n", emp1.emp_name);
    printf("Employee Address: %s, %s, %d\n", emp1.emp_address.street, emp1.emp_address.city, emp1.emp_address.zip_code);

    return 0;
}
Output:

Employee ID: 101
Employee Name: John Doe
Employee Address: Main Street, New York, 10001
Explanation:
In the sample code, first define an inner structure Address, which holds address-related information (city, street, and zip code). Then, define an outer structure Employee, which contains employee details (employee ID, employee name, and address). The outer structure has a member of type struct Address, which represents the address information of the employee. This creates a nested structure. In the main function, declare and initialize an instance of the outer structure emp1, along with its nested structure emp_address. Use dot notation to access and print the information stored in the nested structures. Nested structures are useful when want to organize related data together, creating a more structured and readable code. They help in modelling complex data structures, such as representing real-world entities with multiple attributes.

What is a nested structure in C?


Structure

What is the purpose of nesting structures in C?


Composition

How do you access members of a nested structure in C?


Dot