Array of Struct

If we want many variables of the same structure then we can make an array of structure variables. Because it is time consuming to make many variables of the same structure. Let us understand this by an example. In the below example, structure str has 3 variables: stu1, stu2. stu3,

struct str{

int roll_no;

float percentage;

char name[20];

}stu1,stu2,stu3;

Here there are only 3 variables (stu1,stu2,stu3) of the same structure but if we want to take data of 100 students then we need to make 100 variables like stu1, stu2, …,stu99. So as the solution to this problem we can make an array of structures. This array is similar to an array of a simple variable. The syntax is as below

data type 1> <member variable name 1>;

<data type 2> <member variable name 2>;

//and so on

}<structure variable>[index of array];

Let us do the same example (previous example) using array structure.

struct str{

int roll_no;

float percentage;

char name[20];

}stu[3];

Here the method of accessing members of the structure is the same. Just instead of the structure variable name, we have to use the structure variable name with its array index.

Example program of using an array of structure

In the below program, structure str has 3 members: roll_no, percentage, name. Variable of structure is an array “stu”. Array “stu” has 3 indexes. Using dot “.” Operator values are given to structure members and then all are printed.

#include<stdio.h>
#include<conio.h>
#include<string.h>
struct str{
int roll_no;
float percentage;
char name[20];
}stu[3];

void main()
{
  clrscr();
  stu[0].roll_no=12,strcpy(stu[0].name,"Ram"),stu[0].percentage=77.6;
  stu[1].roll_no=24,strcpy(stu[1].name,"Raman"),stu[1].percentage=87.9;
  stu[2].roll_no=36,strcpy(stu[2].name,"Om"),stu[2].percentage=69.4;

  printf("stu1 : %d %s %f \n",stu[0].roll_no,stu[0].name,stu[0].percentage);
  printf("stu2 : %d %s %f \n",stu[1].roll_no,stu[1].name,stu[1].percentage);
  printf("stu3 : %d %s %f \n",stu[2].roll_no,stu[2].name,stu[2].percentage);
  getch();
}

Output:

Learning from this blog:

1) What is the need of using an array of structure?
2) Syntax to use an array of structure.
3) How to access a member of a structure array.
4) Difference between the array of simple variables and structure variables.
5) How to make a program by making an array of structures.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments