A structure can be member of another structure . This is known as nesting of structure or structure within structure.
Ex,
struct date
{
int d;
int m;
int y;
};
struct student
{
int no;
char name[20];
struct date birthdate;
};
Here, the third member of structure is of type date which itself a structure.The variable of structure can be declared as:
struct student s1;
The member birthdate can be accessed as:
s1.birthdate.d=21;
The structure definition can also be written as:
struct student
{
int no;
char name[20];
struct date
{
int d;
int m;
int y;
}birthdate;
};
Example
// Structure within structure
#include<stdio.h>
#include<conio.h>
struct stud
{
int sno;
char sname[15];
struct bdate
{
int d;
int m;
int y;
}b;
};
void main()
{
struct stud s;
clrscr();
printf("\n Enter roll no : ");
scanf("%d",&s.sno);
fflush(stdin);
printf("\n Enter name : ");
gets(s.sname);
printf("\n Enter birth date : dd-mm-yy : ");
scanf("%d %d %d",&s.b.d,&s.b.m,&s.b.y);
printf("\n----------------------- ");
printf("\n Roll number : %d",s.sno);
printf("\n Name : %s",s.sname);
printf("\n Birth date : %d - %d - %d",s.b.d,s.b.m,s.b.y);
getch();
}
Posted By : Ruchita Pandya
No comments:
Post a Comment