Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

C Nested Structures

We can define one structure inside another structure.

Method 1

struct<struct1_name>
{
    // struct1 members

    struct<struct2_name>
    {
        // struct2 members
    }variable1, variable2, ---, variableN;
};

Example

struct Employee
{
    int id_no;
    char name[50];
    float salary;
    struct Address
    {
        char city_name[30];
        int pin_no;
    }addr;
};

struct Employee emp1,emp2;

Another way of nesting structure

Method 2

struct<struct1_name>
{
    // struct1 members
};

struct<struct2_name>
{
    // struct2 members
    struct struct1_name variable; // structure as a member of another structure

}variable1, variable2, ---, variableN;

Example

struct Address
{
    char city_name[30];
    int pin_no;
};

struct Employee
{
    int id_no;
    char name[50];
    float salary;
    struct Address addr; // structure as a member of another structure
};

struct Employee emp1,emp2;

Way to access nested structure member

outer_structure_variable.inner_structure_variable.inner_structure_member

Example

emp1.id_no;
emp1.name;
emp1.salary;
emp1.addr.city_name; // nested structure member
emp1.addr.pin_no; // nested structure member

emp2.id_no;
emp2.name;
emp2.salary;
emp2.addr.city_name; // nested structure member
emp2.addr.pin_no; // nested structure member

Example

#include<stdio.h>

struct Employee
{
    int id_no;
    char name[50];
    float salary;
    struct Address
    {
        char city_name[30];
        int zip_code;
    }addr;
}emp1={11,"JOHN",55000.65,{"New York",10001}};

int main()
{
    printf("\n ID NO. = %d",emp1.id_no);
    printf("\n Name = %s",emp1.name);
    printf("\n Salary = %f",emp1.salary);
    printf("\n City = %s",emp1.addr.city_name);
    printf("\n ZIP = %d",emp1.addr.zip_code);

    return 0;
}

Output

ID NO. = 11
Name = JOHN
Salary = 55000.648438
City = New York
ZIP = 10001

Note

Any number of structures can be nested inside another structure. There is no limitation.

 

Leave a reply