- We can create an array of structure just like we create an array of built in data type such as int, float etc.
- A single structure variable can store only information of single entity. In other words, a single structure variable can store only single record.
- Consider the following structure variable declaration of emp structure. Variable e1 can be used to store record of single employee only.
struct emp e1;
- In practical life we need to store multiple records of multiple employees with common information for all.
- In this case we can simply declare a structure variable as an array just like normal array declaration of basic data types which is called Array of Structure.
- The only difference is that in array of structure each array element will be of type structure.
Syntax | Example |
---|---|
struct tag_name { data-type var-name1; data-type var-name2; : data-type var-nameN; }; |
struct product { int pid; char name[20]; int qnt; float price; }; |
struct tag_name struct_var[size]; | struct product p1[3]; |
- Note that structure variable p1 is declared as an array of structure. Memory representation for p1 will be as follow:
- Structure variable p1 can store three records of product and we can access each individual record using array index along with structure variable name just like normal array.
- For example to access first record or element we can simply use p1[0], to access second and third record p[1] and p1[2]
- Individual member of structure can be accessed with the same method as we did before i.e. using dot operator along with structure variable name and member name.
- For example, to access individual members of first record we can do so as follow:
Syntax:
struct_var_name [index] . member_name
Example:
P1[0].pid = 101;
- Consider the following example where we have used array of structure to store records of five employees.
//Program to declare array of structure to store records of five employees.
#include "stdio.h"
#include "conio.h"
struct product // structure declaration
{
int pid;
char name[20];
int qnty;
float price;
};
void main()
{
struct product p1[5]; //structure variable declaration where P1 is array of structure
int i;
for( i = 0 ; i < 5 ; i++) //read data
{
printf(“\n Enter Prduct ID, Name, QNT and Price :” ) ;
scanf(“%d %s %d %f”, &p1[i].pid, &p1[i].name, &p1[i].qnty,
&p1[i].price);
}
printf(“\n ID\tName\tQNT\tPrice” ) ;
for( i = 0 ; i < 5 ; i++) // print data
{
printf(“\n%d %s %d %f”, p1[i].pid, p1[i].name, p1[i].qnty,
p1[i].price);
}
getch();
}