Public App

a blog about technology

The Array of Structures in C Language

In C language, you can define an array of structures, which is a collection of structures of the same type. This allows you to store and access multiple instances of the same structured data type in a contiguous block of memory.

Here’s an example of how to define an array of structures:

#include <stdio.h>

struct student {
    char name[50];
    int age;
    float gpa;
};

int main() {
    // Declare an array of 3 student structures
    struct student class[3];

    // Set values for the first student
    strcpy(class[0].name, "John Smith");
    class[0].age = 19;
    class[0].gpa = 3.2;

    // Set values for the second student
    strcpy(class[1].name, "Jane Doe");
    class[1].age = 20;
    class[1].gpa = 3.8;

    // Set values for the third student
    strcpy(class[2].name, "Bob Johnson");
    class[2].age = 18;
    class[2].gpa = 2.9;

    // Print out the information for all three students
    for (int i = 0; i < 3; i++) {
        printf("Student %d:\n", i + 1);
        printf("Name: %s\n", class[i].name);
        printf("Age: %d\n", class[i].age);
        printf("GPA: %.2f\n\n", class[i].gpa);
    }

    return 0;
}

In this example, we first define a struct called student, which contains three members: a character array for the student’s name, an integer for their age, and a floating-point number for their GPA.

We then declare an array of three student structures called class. We set the values for each student by accessing the corresponding element of the array using the index operator [ ]. Finally, we print out the information for all three students using a for loop.

Arrays of structures are useful for organizing and manipulating related data, such as records in a database or items in an inventory.

Amitesh Kumar

Leave a Reply

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

Back to top