Array of Structures in C

Declaring an array of structure is same as declaring an array of fundamental types. Since an array is a collection of elements of the same type. In an array of structures, each element of an array is of the structure type.

Let’s take an example:

Here is how we can declare an array of structure car.

an-array-of-structure

Here arr_car is an array of 10 elements where each element is of type struct car. We can use arr_car to store 10 structure variables of type struct car. To access individual elements we will use subscript notation ([]) and to access the members of each element we will use dot (.) operator as usual.

and so on. Similarly,

Recall that the precedence of [] array subscript and dot(.) operator is same and they evaluates from left to right. Therefore in the above expression first array subscript([]) is applied followed by dot (.) operator. The array subscript ([]) and dot(.) operator is same and they evaluates from left to right. Therefore in the above expression first [] array subscript is applied followed by dot (.) operator.

Let’s rewrite the program we used in the last chapter as an introduction to structures.

Expected Output:

How it works:

In lines 5-10, we have declared a structure called the student.

In line 14, we have declared an array of structures of type struct student whose size is controlled by symbolic constant MAX. If you want to increase/decrease the size of the array just change the value of the symbolic constant and our program will adapt to the new size.

In line 17-29, the first for loop is used to enter the details of the student.

In line 36-40, the second for loop prints all the details of the student in tabular form.

Initializing Array of Structures

We can also initialize the array of structures using the same syntax as that for initializing arrays. Let’s take an example:

Leave a Comment