Nested Structure (Structure Within Structure) in C with Examples

In C programming, we can have members of a structure itself as a structure. This is also referred to as structure within structure and such types of structures are known as nested structure.

Nested Structure Example

Consider the following scenario:


/* normal structure */
struct address
{
 int houseno;
 char street[20];
 int stateno;
};

/* nested structure */
struct student
{
 char name[30];
 int roll;
 struct address adr; /* structure within structure or nested structure */
};

struct student  st; /* structure variable */

In the above scenario, address is normal structure which contains three members houseno, street and stateno. But, student is nested structure because it contains member address which is of type struct.

Understanding Nested Structure

In above example, structure address is defined first with member houseno, street & stateno. This is normal structure i.e. there is no nesting. But, the structure student having memeber name, roll & adr is nested structure because the member adr is type of another user created structure. So, structure student is nested because of member adr.

Accessing Elements in Nested Structure

The elements of nested structures are accessed from outermost to innermost with the help of . (dot) operator. For example, to access houseno, we use st.adr.houseno, similarly for street, we use st.adr.street, and so on.

C Program: Nested Structure Example


#include<stdio.h>

/* Declaration of structure */
struct address
{
 int houseno;
 char street[20];
 int stateno;
};

/* Declaration of structure */
struct student
{
 char name[30];
 int roll;
 struct address adrs;   /* Nested structure */
};

int main()
{
 struct student stud;

 printf("Enter name and roll number of student:\n");
 scanf("%s%d",stud.name, &stud.roll);
 printf("Enter street name, house number and state number:\n");
 scanf("%s%d%d",stud.adrs.street, &stud.adrs.houseno, &stud.adrs.stateno);
 printf("Student detail is:\n");
 printf("Name: %s\tRoll: %d\n", stud.name, stud.roll);
 printf("Address:%s, House no. -%d, state: %d",stud.adrs.street, stud.adrs.houseno, stud.adrs.stateno);
 
 return 0;
}

The output of the above program is:

Enter name and roll number of student:
Ramesh ↲
17 ↲
Enter street name, house number and state number:
Jwagal ↲
78 ↲
3 ↲
Student detail is:
Name: Ramesh             Roll: 17
Address: Jwagal, House no. – 78, state: 3 

Note: ↲ represents ENTER key is pressed.