ARRAY OF STRUCTURE IN C

     ARRAY OF STRUCTURE IN C

An object of the structure represents a single record in memory if we want more than one record of structure type. As we know, an array is a collection of similar types, therefore an array can be of structures type. It is simply an array in which each element is a structure at the same time.

 An array of structures can be accessed by indexing just as we access an array. An array of structures find the application in grouping the records together and provides for fast access.

Structural Declaration:

struct name

{

   datatype member1;

   datatype member2;

   datatype member3;

}

Whenever we declare variable structure gets memory allocation.

The following example of an array of structures is:

struct emp{

int id;

int sal;

char name[20];

};

 

For example,

struct emp e1;

It will store records for one employee,

If we want to store 100 employee records, so a declaration of 100 variables is a complex task

So, we go for the array.

Syntax

 struct emp e[3];

Defines an array called e that consists of 3 elements. Each element is defined to be of the type struct student.

We are creating an array of emp structure variable e of size 3 to hold details of three employees.

//emp structure

struct emp{

int id;

int sal;

char name[20];

};

struct emp e[3];    //emp structure variable

ARRAY OF STRUCTURE

Below is the code of the array of structures. The array holds records of the employee. The records contain the id, name, address, and salary which have been grouped under the structure(a record).

 

Complete code:

#include<stdio.h>
#include<conio.h>
Struct employee
{
    int eid;                          //data member of employeee
    char ename[50];
    char eadd[100];
    int esal;
};
void main()
{
    struct employee emp[3];            // for storing 3 employee info 
    int i,total=0;
    clrscr();
for(i=0;i<10;i++)
{
    printf(“Enter the employee id\n”);
    scanf(“%d”,&emp[i].eid);
    printf(“Enter the employee name\n”);
    scanf(“%d”,&emp[i].ename);
    printf(“Enter the employee address\n”);
    scanf(“%d”,&emp[i].eadd);
    printf(“Enter the employee salary\n”);
    scanf(“%d”,&emp[i].esal);
}
for(i=o;i<10;i++)
{
printf(“employee id is %d\n”,emp[i].eid);
printf(“employee name is %d\n”,emp[i].ename);
printf(“employee address is %d\n”,emp[i].eadd);
printf(“employee salary is %d\n”,emp[i].esal);
}
getch();
}

Output:

Enter the employee id

1

Enter the employee name

ABC

Enter the employee address

XYZ

Enter the employee salary

1000

Enter the employee id

2

Enter the employee name

MNO

Enter the employee address

EFG

Enter the employee salary

2000

Enter the employee id

3

Enter the employee name

JKL

Enter the employee address

EFG

Enter the employee salary

8000

 

Also, read a pointer that points to an array in C.

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *