C Nested Structure

C Nested structure:

A C Nested Structure can be defined in two ways:

By separate structure:

Defining a Nested Structure by separate structure simply means to use a structure inside another structure as a member of that structure. In this way, a single structure can be used in many structures.

Example 1:

#include<stdio.h>  
#include <string.h>
 
struct Date  
{  
int dd;  
int mm;  
int yyyy;   
};
 
struct student 	 
{   
int roll_no; 	 
char name[30];  
struct Date doj;
}s;  
 
void main( )    
{  
s.doj.dd=21;  
s.doj.mm=9;  
s.doj.yyyy=2014;  
s.roll_no = 1;    
strcpy(s.name, "Vibhuti Singh");
 
printf( "Student Date of Joining (D/M/Y) : %d/%d/%d\n", s.doj.dd,s.doj.mm,s.doj.yyyy);  
printf( "Student Enrollment No. : %d\n", s.roll_no);    
printf( "Student Name : %s\n\n", s.name);  
}

Output

Student Date of Joining (D/M/Y) : 21/9/2014
Student Enrollment No. : 1
Student Name : Vibhuti Singh

By Embedded structure

Defining a Nested Structure by embedded structure simply means to define a structure inside another structure. In this way, number of code lines decreases, however, a single structure can not be used in other structures.

Example 2:

#include<stdio.h>  
#include <string.h>
 
struct student 	 
{   
int roll_no; 	 
char name[30];  
struct Date  
{  
int dd;  
int mm;  
int yyyy;   
}doj;  
}s;  
 
void main( )    
{  
s.doj.dd=21;  
s.doj.mm=9;  
s.doj.yyyy=2014;  
s.roll_no = 1;    
strcpy(s.name, "Vibhuti Singh");
 
printf( "Student Date of Joining (D/M/Y) : %d/%d/%d\n", s.doj.dd,s.doj.mm,s.doj.yyyy);  
printf( "Student Enrollment No. : %d\n", s.roll_no);    
printf( "Student Name : %s\n\n", s.name);  
}

Output

Student Date of Joining (D/M/Y) : 21/9/2014
Student Enrollment No. : 1
Student Name : Vibhuti Singh

Accessing a member of Nested Structure:

Syntax:

Outer_Structure.Nested_Structure.member