Nested Structures in C

A structure can be nested inside another structure. In other words, the members of a structure can be of any other type including structure. Here is the syntax to create nested structures.

Syntax:

Note: Nesting of structures can be extended to any level.

To access the members of the inner structure, we write a variable name of the outer structure, followed by a dot(.) operator, followed by the variable of the inner structure, followed by a dot(.) operator, which is then followed by the name of the member we want to access.

var2.var1.member_1 – refers to the member_1 of structure tagname_2
var2.var1.member_2 – refers to the member_2 of structure tagname_2

and so on.

Let’s take an example:

Here we have defined structure person as a member of structure student. Here is how we can access the members of person structure.

stu.p.name – refers to the name of the person
stu.p.age – refers to the age of the person
stu.p.dob – refers to the date of birth of the person

It is important to note that structure person doesn’t exist on its own. We can’t declare structure variable of type struct person anywhere else in the program.

Instead of defining the structure inside another structure. We could have defined it outside and then declare it’s variable inside the structure where we want to use it. For example:

We can use this structure as a part of a bigger structure.

Here the first member is of type struct person. If we use this method of creating nested structures then you must first define the structures before creating variables of its types. So, it’s mandatory for you to first define person structure before using it’s variable as a member of the structure student.

The advantage of using this method is that now we can declare a variable of type struct person in anywhere else in the program.

Nesting of structure within itself is now allowed. For example:

Initializing nested Structures

Nested structures can be initialized at the time of declaration. For example:

The following program demonstrates how we can use nested structures.

Expected Output:

How it works:

In lines 3-8, we have declared a structure called person.

In lines 10-15, we have declared another structure called student whose one of the members is of type struct student (declare above).

In line 19, we have declared a variable s1 of type struct student.

The next five scanf() statements (lines 23-36) asks the user to enter the details of the students which are then printed using the printf() (lines 40-44) statement.

Leave a Comment