Nested structure in c

Nesting the structure within another structure is termed as the nested structure in c. 

What is nesting of structure?

Consider, we have defined more than one structure in a program. If we want to access the structure members of one structure in another structure, then we can define the structure variable of that structure in another structure. This concept is defined as the nesting of structure, or structure within a structure in c.

 

What are structure members?

Structure members are the variables defined inside the structure. 

 

What is structure_variable_name?

Structure_variable_name is the variable declared to the user-defined structure datatype.



Nested-structure-c

struct structure_name1 is the inner structure, and struct structure_name2 is the outer structure. 

we have to access the structure members of inner structure using the outer structure.

How do we access the structure members of the inner structure using outer structure?

 We have to access it using the dot (•) operator. 

In normal structure, for operating the structure member, we write structure_variable_name•structure_member.

For accessing the nested structure we write, 

structure2_variable_name•structure1_variable_name•structure1_member_name.

Outer structure variable name must be at the prefix of the inner structure variable name. 

Note: we can nest as many structures as we want. 

And to access the structure_member Of any nested structure, we have to write the nested structure_variable_name on the inner side.

structure_variable_name of outer structure(structure inside which the nested structure name has declared), should be at the prefix of the nested structure_variable_name.

Let us have a look at the program. 

1. Nested structure in c (defining the structure outside the main function) globally. 

2. Nested structure in c (Defining the structure inside the main function).

1. Nested structure in c (defining the structure outside the main function) globally. 

#include <stdio.h>
struct employee
{
  long int id_no;
  int age;
};
struct company
{
 char name[10];
 struct employee e;
};
int main() 
{
  struct company c;
  printf("Enter the details:");
  
 scanf("%s%ld%d",c.name,&c.e.id_no,&c.e.age);
 printf("\nname= %s \nid_no= %ld\n age= %d",c.name,c.e.id_no,c.e.age);
return 0;
}
Output:

Enter the details:
TCS
3456
25
name= TCS
 id_no= 3456
age= 25

2. Nested structure in c (Defining the structure inside the main function).

#include <stdio.h>
int main() 
{
struct employee
{
  long int id_no;
  int age;
};

struct company
{
 char name[10];
 struct employee e;
};
struct company c;
  
 printf("Enter the details:");
 scanf("%s%ld%d",c.name,&c.e.id_no,&c.e.age);
 printf("\nname= %s \id_no= %ld\n age= %d",c.name,c.e.id_no,c.e.age);
return 0;
}
Output:

Enter the details:
TCS
3456
25
name= TCS
 id_no= 3456
age= 25