nested structure in c

nested structure in c

The members of a structure can be a of any data type including another structure type. so we can declare or include structure with in another structure. so in this A structure variable can be a member of another structure.This is called nesting of structures.

.

struct tag0
{
member1;
member2;
member3;
…….
struct tag1
{
member1;
member2;
member3;
…….
}var1;
…..
….
member n;
}var2;

for accessing member1 of inner structure struct tag2 we write

var2.var1.member1

struct Employee
{
char name[15];
int empid;
struct date
{
int day;
int month;
int year;
}birthinfo;
float salary;
}
emp1,emp2;

so in this example we have defined a structure date with in Employee structure. The structure date has three members day,month and year and birthinfo is the variable of type struct date. we can access the members of inner structure as

emp1.birthinfo.day day of birthinfo of emp1
emp1.birthinfo.month month of birthinfo of emp1
emp1.birthinfo.year year of birthinfo of emp1
emp2.birthinfo.day day of birthinfo of emp2

so we have defined the template of the structure date inside the strucure Employee, we also can defined it outside and declare its variables inside the structure Employee using the tag. but always remember if we define the inner structure outside, then this defination should always be before the defination of outer structure. now take the example in this example date structure should be defined before the Employee structure

struct date {
int day;
int month;
int year;
};
struct Employee
{
char name[20];
int empid;
int salary;
struct date birthinfo;
}emp1,emp2;

struct Employee
{
char name[15];
int empid;
int salary;
struct date joindate,leavedate;
}emp1,emp2;