Array of Structure in C with Examples

An array having structure as its base type is known as an array of structure. To create an array of structure, first structure is declared and then array of structure is declared just like an ordinary array.

Example: Array of Structure

If struture is declared like:


struct employee
{
 int emp_id;
 char name[20];
 char dept[20];
 float salary;   
};

Then an array of structure can be created like:


struct employee emp[10]; /* This is array of structure */

Explanation

In this example, the first structure employee is declared, then the array of structure created using a new type i.e. struct employee. Using the above array of structure 10 set of employee records can be stored and manipulated.

Acessing Elements from Array of Structure

To access any structure, index is used. For example, to read the emp_id of the first structure we use scanf(“%d”, emp[0].emp_id); as we know in C array indexing starts from 0.


Similar array of structure can also be declared like:


struct employee
{
 int emp_id;
 char name[20];
 char dept[20];
 float salary;   
}emp[10];

Similarly, we can use typedef to create similar array of structure as:


typedef     struct
{
 int emp_id;
 char name[20];
 char dept[20];
 float salary;   
}employee;

employee emp[10];

C Program: Array of Structure

C program to read records of three different students in structure having member name, roll and marks, and displaying it.

C Source Code:


#include<stdio.h>

/* Declaration of structure */
struct student
{
 char name[30];
 int roll;
 float marks;
};

int main()
{
 /* Declaration of array of structure */
 struct student s[3];
 int i;

 for(i=0;i< 3;i++)
 {
  printf("Enter name, roll and marks of student:\n");
  scanf("%s%d%f",s[i].name, &s[i].roll, &s[i].marks);
 }
 printf("Inputted details are:\n");
 for(i=0;i< 3;i++)
 {
  printf("Name: %s\n",s[i].name);
  printf("Roll: %d\n", s[i].roll);
  printf("Marks: %0.2f\n\n", s[i].marks);
 }
 
 return 0;
}

Output

Enter name, roll and marks of student:
Manjari↲
17↲
80.5↲
Enter name, roll and marks of student:
Monalisa↲
18↲
90↲
Enter name, roll and marks of student:
Manita↲
19↲
78↲
Inputted details are:
Name: Manjari
Roll: 17
Marks: 80.50

Name: Monalisa
Roll: 18
Marks: 90.00

Name: Manita
Roll: 19
Marks: 78.00