ADVERTISEMENT
ADVERTISEMENT

What is Array of Structure in C ?

In C, an array of structures is a collection of many structure variables, each of which holds information about separate entities. Each element of the array is a structure variable that contains multiple members of different data types.

Syntax for defining an array of structures in C 

struct struct_name
{
    member1;
    member2;
    member3;
    .
    .
    .
};

struct struct_name array_name[size];  // Array of Structure

For example, the following code defines an array of structures named "Student" that contains 3 elements:

struct Student 
{
    int marks;
    char name[20];
};

struct Student s[3];  // Array of Structure

Here, an array of 3 structures of type Student is created. Each element of the array is a structure variable that contains two members: an integer variable "marks" and a character array "name".

Here's a simple C program that demonstrates the use of an array of structures:

#include <stdio.h>
struct Employee
{
    char name[20];
    int age;
    float salary;
};

int main() 
{
    struct Employee e[3];
    for (int i = 1; i < 4; i++)
    {
        printf("Enter details of employee %d:", i);
        printf("Name: ");
        scanf("%s", e[i].name);
        printf("Age: ");
        scanf("%d", &e[i].age);
        printf("Salary: ");
        scanf("%f", &e[i].salary);
    }

    printf("Employee details:");
    for (int i = 0; i < 3; i++)
   {
        printf("Name: %s", e[i].name);
        printf("Age: %d", e[i].age);
        printf("Salary: %.2f", e[i].salary);
    }

    return 0;
}

In this program, a structure named "Employee" is defined that contains three members: a character array named "name", an integer variable named "age", and a float variable named "salary". An array of structures named "e" of size 3 is created. The program prompts the user to enter the details of 3 employees, stores them in the array of structures, and then displays the details of all the employees using a loop.

This program allows the user to enter the details of 3 employees, stores the details in an array of structures, and then prints the details of all the employees.


ADVERTISEMENT

ADVERTISEMENT