/    /  Array of Structures

Array of Structures

 

An array of structures, the variable of the structure is an array. In our sample program, to store details of 100 students we would be required to use 100 different structure variables from s1 to s100,which is definitely not very convenient. A more appropriate approach would be to use an array of structures.

 

The Syntax for declaring structure array:

 

struct struct-name
{
datatype var1;
datatype var2;
- - - - - - - - - -
- - - - - - - - - -
datatype varN;
};
struct struct-name obj [ size ];

 

Example program:

 

To read and display the information of ‘n’ number of students where n is value supplied by user.

 

#include<stdio.h>
#include<string.h>
struct student
{
int rno;
char name[10];
int marks,age;
};
void main()
{
struct student s[10];//Declares array of 10 student.
int i,n;
printf("\n enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
//reading values for s3 using standard input function.
printf("\n enter rno,name ,marks,age of student %d: ",i+1);
scanf("%d%s%d%d",&s[i].rno,s[i].name,&s[i].marks,&s[i].age);
}
printf("\n\n");
printf("Details of students are :\n");
for(i=0;i<n;i++)
{
printf("\n Details of student %d:\n",i+1);
printf("\n roll number: %d",s[i].rno);
printf("\n name :%s",s[i].name);
printf("\n marks: %d",s[i].marks);
printf("\n age: %d",s[i].age);
}
}

 

Output:

 

Array of Structures

 

In the above program, the memory allocated for the structure variable is 160 bytes consecutively in which first 16 bytes for 1st student 1(s[0]),next 16 bytes for 2nd student 2(s[1]) and so on last 16 bytes for 10th student (s[9]).

 

The following figure shows the memory allocation for an array of structures:

 

Array of Structures