Nested structs c – Nesting of Structures in C Programming

Nested structs c: Nesting of structures is supported in C programming language. We can declare a structure variable as member of structure or write one Structure inside another structure.

There are two ways to define nested structure in C language.

Declaring a Structure Variable as Member of Another Structure

In this approach, we create two structures and include a structure variable as member variable of another structure.

struct Address  
{  
   int houseNumber;  
   char street[100];  
   char zipCode;
};

struct Employee  
{     
   char name[100];  
   int age;
   float salary;
   struct Address address;
} employee; 

In above declaration, we have included a variable of structure Address as member of structure Employee.

Declaring a Structure inside Another Structure

In this approach, we declare a structure inside curly braces of another structure.

struct Employee  
{     
   char name[100];  
   int age;
   float salary;
   struct Address  
   {  
      int houseNumber;  
      char street[100];  
      char zipCode;
   } address;
} employee;

The normal data members of a structure is accessed by a single dot(.)operator but to access the member of inner structure we have to use dot operator twice.

Outer_Structure_variable.Inner_Structure_variable.Member

For Example
In above example, we can access zipCode of inner structure as

employee.address.zipCode

C Program to Show Nesting of Structure

In below program, we declare a structure “employee” which contains another structure “address” as member variable.

Nesting of Structures in C Programming

#include <stdio.h>
#include <conio.h>
 
struct employee {
    char name[100];
 int age;
 float salary;
 struct address {
        int houseNumber;
        char street[100];
    }location;
};
 
int main(){
   struct employee employee_one, *ptr;
    
   printf("Enter Name, Age, Salary of Employee\n");
   scanf("%s %d %f", &employee_one.name, &employee_one.age,
       &employee_one.salary);
    
   printf("Enter House Number and Street of Employee\n");
   scanf("%d %s", &employee_one.location.houseNumber,
       &employee_one.location.street);
        
   printf("Employee Details\n");
   printf(" Name : %s\n Age : %d\n Salary = %f\n House Number : %d\n Street : %s\n", 
       employee_one.name, employee_one.age, employee_one.salary,
       employee_one.location.houseNumber, employee_one.location.street);
 
   getch();
   return 0;
}

Output

Enter Name, Age, Salary of Employee
Jack 30 1234.5
Enter House Number and Street of Employee
500 Street_One
Employee Details
 Name : Jack
 Age : 30
 Salary = 1234.500000
 House Number : 50
 Street : Street_One