C Nested Structures


Structure within the structure is called nesting of structures. It is permitted in C.

 

Consider following structure illustrated to store particulars about the salary of employees.

 

struct salary{
	char name[20];
	char department[10];
	int basic_pay;
	int health_allowance;
	int house_rent_allowance;
}employee;

 

This structure defines name, department, basic pay and two kinds of allowances. We can able group all the items related to allowance together and declare them under a sub-structure as:

 

struct salary{
	char name[2];
	char department[10];
	struct{
		int health;
		int house_rent;
        }allowance;
}employee;

 

The salary structure contains a member named allowance which itself is a structure with two members. The members contained in the inner structure namely health and house_rent can be referred to as

 

employee.allowance.health

 

employee.allowance.house_rent

 

An inner member in a nested structure can be acquired by chaining all the troubled structure variables with the member using dot operator.


Example:

#include <stdio.h>
#include <stdlib.h>   
  
struct student      
{   int id;      
    char name[50];    
	struct marks{  //Nested structure
    	int mark1;
		int mark2;     
	}mark; 
}s[3]; 

void main( )    
{    
    s[1].id=101;    
    strcpy(s[1].name, "Arunkumar");
    s[1].mark.mark1=89;    
    s[1].mark.mark2=58; 
    
    s[2].id=105;    
    strcpy(s[2].name, "Manivannan");
    s[2].mark.mark1=69;    
    s[2].mark.mark2=88; 
    
    s[3].id=102;    
    strcpy(s[3].name, "Deepalakshmi");
    s[3].mark.mark1=79;    
    s[3].mark.mark2=98; 

    for(int i=1;i<4;i++){
    printf( "Student %d id : %d\n",i, s[i].id);    
    printf( "Student %d name : %s\n",i, s[i].name);    
    printf( "Student %d mark1 : %d\n",i, s[i].mark.mark1);    
    printf( "Student %d mark2 : %d\n",i, s[i].mark.mark2); 
    }
}



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.