array of structure

array of structure is combination of two different concept, are following:-

using the array of structure, we can create all the elements of an array in a structure type element, which means that every element of the array is a structure. which stores the array structure and structure different data type (data member).

You can understand this with the help of diagram given below-

array-of-structure

Here arr[4] is array type variable of a structure.

as you can see above, structure -variable name is same but  due to different index value, structure-variable are different each other. 

In array of structure we make structure-variable as array variable. its syntex is given below-


Declaration of a  structure-variable

Here is the SYNTEX, below

structure_name structure_variable[size];

In this we first declare structure members and then declare the array variable of a structure-variable such as,

struct student{
   int roll,age
   char name[10];
  };
book vr[2];

In the above structure declaration, we have stored the record (roll, age and name) of two students using the array of structure.

For 1st student

vr[0].roll;
vr[0].age;
vr[0].name;

For 2nd student,

vr[1].roll;
vr[1].age;
vr[1].name;

 as you can see in the below diagram also,

array-with-structure


accessing member in array of structure

Because,here it contains the element of structure and as we know that we use index value to access the array element. So means, the structure will be accessed by index value just like a simple array variable. like-

structure_variable [value].structure_member_name

Let’s try with an example
Example:-

#include<iostream.h>
#include<conio.h>
#include<stdio.h>

// struct declaration outside main() 
struct
{  
  int roll,age;
  char name[20];
}vr[2];

void main()
{
  clrscr();
  for(int i=0; i<2; i++)
  {
     cout<"Enter "<<i+1<<" Student Record\n";
     cout<<"Enter Roll no: ";
     cin>>vr[i].roll;
     cout<<"Enter Name : ";
     gets(vr[i].name);
     cout<<"Enter age : ";
     cin>>vr[i].age;
  }
  cout<<endl;
  for(int j=0; j<2; j++)
 {
    cout<<"\nDisplay "<<j+1<<" Student Record";
    cout<<"\nRoll no.: "<<vr[j].roll;
    cout<<"\nName : "<<vr[j].name;
    cout<<"\nAge : "<<vr[j].age;
  }
  getch();
}
OUTPUT:-
Enter 1 Student Record
Enter Roll no: 10
Enter Name : Rahul sherma
Enter age : 25
Enter 2 Student Record
Enter Roll no: 11
Enter Name : Rohit kumar
Enter age : 24

Display 1 Student Record
Roll no.: 10
Name : Rahul sherma
Age : 25
Display 2 Student Record
Roll no.: 11
Name : Rohit kumar
Age : 24

previous-Structure in C++

next-union in C++