0
0
Cprogramming~5 mins

Array of structures

Choose your learning style9 modes available
Introduction

An array of structures lets you store many related groups of data together. It helps organize information like a list of people, each with their own details.

When you want to keep a list of students, each with a name, age, and grade.
When you need to store multiple books, each with a title, author, and year.
When you want to manage a collection of products, each with an ID, price, and quantity.
When you want to group related data items together and access them by index.
Syntax
C
struct Person {
    char name[50];
    int age;
    float height;
};

struct Person people[10];

You first define the structure type with struct.

Then you create an array of that structure type to hold many items.

Examples
This creates an array of 5 books, each with title, author, and year.
C
struct Book {
    char title[100];
    char author[50];
    int year;
};

struct Book library[5];
An empty array of structures (size 0) means no elements are stored yet.
C
struct Point {
    int x;
    int y;
};

struct Point points[0];
An array with one element can store exactly one item.
C
struct Item {
    int id;
    float price;
};

struct Item singleItem[1];
Sample Program

This program creates an array of 3 students, fills their details, and prints them one by one.

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

struct Student {
    char name[50];
    int age;
    float grade;
};

int main() {
    struct Student students[3];

    // Fill data for each student
    strcpy(students[0].name, "Alice");
    students[0].age = 20;
    students[0].grade = 88.5f;

    strcpy(students[1].name, "Bob");
    students[1].age = 22;
    students[1].grade = 91.0f;

    strcpy(students[2].name, "Charlie");
    students[2].age = 19;
    students[2].grade = 85.0f;

    // Print all students
    printf("List of students:\n");
    for (int i = 0; i < 3; i++) {
        printf("Name: %s, Age: %d, Grade: %.1f\n", students[i].name, students[i].age, students[i].grade);
    }

    return 0;
}
OutputSuccess
Important Notes

Access elements by index: array[index].

Use strcpy to copy strings into char arrays inside structures.

Time complexity to access an element is O(1) because arrays allow direct access.

Remember to not exceed the array size to avoid memory errors.

Summary

An array of structures stores many grouped data items together.

Define the structure first, then create an array of that structure type.

Access each element by its index to read or change data.