Nested Structure

Course- C >

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

 
  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

 
  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

 
  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

 
  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014