Array of Structure

An array is a data structure that holds similar types of data whereas a the structure is the one which can hold data of different types.

Please refer array and structure for better understanding.

Thus an array of structures can be defined as a collection or array of multiple structure variables where each variable contains information about different entries. It is used to store information about multiple entries of different types. The array of structures is also known as the collection of structures.

Example:

Consider a case where information about multiple employees has to be stored. Since information about employees is of different types like name(char), id(int), salary(float). Thus the best suited data structure is structure and since we have multiple employees thus array can be used where each index of array is a structure variable. Hence an array of structures can be used.

c array of structures

C Example:

#include <stdio.h>
#include <string.h>

struct employee
{
   char name[10];
   int id;
   float sal;
};

int main ()
{
   struct employee emp[5];
   int i =0;
   for (i ;i<5;i++)
   {
      strcpy(emp[i].name,"tech");
      emp[i].id =i;
      emp[i].sal = i + 10;
   }
   printf("\n Employee details are:\n");
   for (i=0;i<5;i++)
   {
      printf("\n Employee name is: %s\n",emp[i].name);
      printf("\n Employee id is: %d\n",emp[i].id);
      printf("\n Employee sal is: %f\n",emp[i].sal);
      printf("\n");
   }
   return 0;
}

Output:

Employee details are:

Employee name is: tech

Employee id is: 0
Employee sal is: 10.000000


Employee name is: tech

Employee id is: 1

Employee sal is: 11.000000


Employee name is: tech

Employee id is: 2

Employee sal is: 12.000000


Employee name is tech

Employee id is 3

Employee sal is 13.000000


Employee name is: tech

Employee id is: 4

Employee sal is: 14.000000

Relevant Posts:



Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: