Nesting of Structure in C

Nesting of Structure in C

It is the process of defining one structure within another structure. Nesting of structure can also be applied by taking variable one structure within another structure.

The main advantage of performing nesting is that we can use an existing structure without need to create a new structure for same requirements.

There are two ways to perform nesting of structures in C Language.

First way to declare nesting of structure is that we can take variable of one structure within another structure.

Syntax for performing such type of nesting is:

struct <tag_name1>
{
:
:
};
 struct <tag_name2>
{
struct <tag_name1> Var1;
};




Second way to declare nesting of structure is that we can define one complete structure within another structure.

Syntax for performing such type of nesting is:

struct <tag_name1>
{
:
:
struct <tag_name2>
{
};
 };



Program to demonstrate nesting of structure.
#include<string.h>
#include<stdio.h>
struct dob
{
int day;
int month;
int year;
};
struct student
{
int rollno;
char name[20];
struct dob d;
};
int main()
{
struct student s;
s.rollno=131;
strcpy(s.name,”Lovejot”);
s.d.day=11;
s.d.month=7;
s.d.year=2007;
printf(“\nRollno=%d”,s.rollno);
printf(“\nName=%s”,s.name);
printf(“\nDate of Birth=%d/%d/%d”,s.d.day,s.d.month,s.d.year);
return(0);
}
Output
Rollno=131
Name=Lovejot
Date of Birth=11/7/2007
Description
In the above program, variable d of structure dob has been declared inside the structure student.



Program to demonstrate nesting of structure.
#include<string.h>
#include<stdio.h>
struct student
{
int rollno;
char name[20];
struct dob
{
int day;
int month;
int year;
}d;

};
int main()
{
struct student s;
s.rollno=131;
strcpy(s.name,”Lovejot”);
s.d.day=11;
s.d.month=7;
s.d.year=2007;
printf(“\nRollno=%d”,s.rollno);
printf(“\nName=%s”,s.name);
printf(“\nDate of Birth=%d/%d/%d”,s.d.day,s.d.month,s.d.year);
return(0);
}
Output
Rollno=131
Name=Lovejot
Date of Birth=11/7/2007
Description
In the above program, structure dob has been defined inside the structure student hence implementing nesting of structure.



Best Books of C





Lesson tags: nesting of structure in c, program of nesting of structure in c, structure nesting in c, take a nested structure variable in c
Back to: C Programming Language