Nested Structure

  • Nested structure is structure which has another structure as a member in that structure.
  • A member of structure can be structure itself , this what we call as Nested Structure.
  • Let's understand it by an example.

let's define a structure student with roll no , div and name but should be structure which will have first name , surname as it's attribute.

Defining: structure name
struct name
{
  char first_name[20];

  char surname_name[20];


};

Defining:Structure Student and using struture name as member in structure Student
struct student  //structure name
{
    int  rollno; //member1 ,integer variable which will store,
                 //student roll no.

   

    char  div;  //member2 a character variable,
              //which will store division of student.
    
    struct name n1; //member3 a structure name
                    //which contains first name and
                    //last name as its member.
};

Let's understand visually






Now let's initialize the nested structure.

Initializing:
struct student s1 = {1,A,{"Joel","Anthony"}};

As member3 n1 is a structure name.
that is why we have used another curly braces for member3

Now let's access the member of student structure

Accessing:member rollno and div
main()
{
int s_roll;
char s_div;

//Accessing rollno and assigning
//it to a variable s_roll.
s_roll  = s1.rollno;

//Accessing div and assigning
//it to a variable s_div.
s_div   = s1.div;


}

Now we will Access the member3 n1 which is the structure name.
this is something new which we will going learn now.

Accessing:Member n1
main()
{
char f_name[20]
char s_name[20];

//Accessing first name and assigning
//it to a variable f_name.

strcpy( f_name, s1.n1.first_name);

//Accessing div and assigning
//it to a variable l_name
   strcpy(l_name,s1.n1.last_name);


}

Let's access member n1 individually

Accessing:first_name
s1.n1.first_name;

Accessing:last_name
s1.n1.last_name;

  • This is how we can make a nested structure.
  • There is a another way of defining nested structure but method accessing and initialization of members will remain same
  • Let's see the another method of defining nested structure
  • We will define the same structure student by another method

Defining:structure student by another method
struct student  
{
    int  rollno; //member1 ,integer variable which will store,
                 //student roll no.


    char  div;  //member2 a character variable,
              //which will store division of student.


    struct name
   {
     char first_name[20];   //member3 a structure name
                          //which contains first name and
                           //last name as its member.
     char surname_name[20];


    }n1;//declaring variable n1
        //of structure name data type.

};

  • This is how we can build a nested structure.
  • Do practice on structures for understanding the concept more better.







Further Concept:


People Also Searched: