Nested Structure (Structure within Structure)


When a structure is defined inside another structure then it is known as structure within structure. It is also known as Nested Structure.

Example
struct Student
{
    int rollno;
    char name[20];
      struct mark
    {
       int sub1;
       int sub2;
       int sub3;
    }m1;
}S1;

In above example structure mark is defined inside structure Student. Here, Student is known as outer structure while mark is known as inner structure. So variable m1 of structure mark is also data memebr of structure Student.

     
Data memebr of inner structure can be accessed using variable of outer structure followed by dot (.) operator followed by variable of inner structure followed by dot (.) operator followed by Data memebr.

Example
#include<stdio.h>
#include<conio.h>
struct student
{
   int rollno;
   char name [20];
   struct mark
   {
      int sub1;
      int sub2;
      int sub3;
   }m1;
};
void main ()
{
   clrscr ();
   struct student s[60];
   int i;
   for (i=0; i<60; i++)
   {
      printf ("Enter Roll Number:");
      scanf ("%d", &s[i].rollno);
      printf ("Enter Name:");
      scanf ("%s", s[i].name);
      printf ("Enter Marks of sub1:");
      scanf ("%d", &s[i].m1.sub1);
      printf ("Enter Marks of sub2:");
      scanf ("%d", &s[i].m1.sub2);
      printf ("Enter Marks of sub3:");
      scanf ("%d", &s[i].m1.sub3);
   }
   for (i=0; i<60; i++)
   {
      printf ("Roll Number: %d\n", s[i].rollno);
      printf ("Name: %s\n", s[i].name);
      printf ("Sub1:%d\n", s[i].m1.sub1);
      printf ("Sub2:%d\n", s[i].m1.sub2);
      printf ("Sub3:%d\n", s[i].m1.sub3);
   }
   getch ();
}

Download Projects


Download Programs