Course contentsShow
← C
Lesson 630 of 1,2199. Structures and UnionsFree lesson

Declaring an array of structs

Declaring an array of structs

What you'll learn: How to group multiple structure variables into a single, organized list for easier data management.

The Power of a List

Up to this point, you have learned how to create a struct to represent a single item, like a specific book or a single player in a game. But what happens if you are building a library or a sports team?

Declaring individual variables like player1, player2, and player3 becomes messy very quickly. Instead, you can treat your custom struct just like an int or a char and put it into an array. Think of a structure as a single filing folder; an array of structures is the entire filing cabinet, holding many folders of the exact same layout.

How to Declare It

To declare an array of structures, you first define the structure template, then declare the array using the struct keyword followed by the tag name, your chosen array name, and the size in square brackets.

struct Student {
    char name[50];
    int id;
    float gpa;
};

int main() {
    // Declaring an array capable of holding 100 Student structures
    struct Student classroom[100];

    // Accessing the first student in the array
    classroom[0].id = 101;
    
    return 0;
}

In the example above, classroom is not just one student—it is a contiguous block of memory large enough to hold 100 separate Student structures. Each element in the array (classroom[0], classroom[1], etc.) is a complete structure with its own name, id, and gpa.

Memory and Organization

When you declare struct Student classroom[100], C sets aside a large "apartment building" of memory. Every "apartment" (index) has the exact same floor plan (the structure members). This is incredibly useful because it allows you to use for loops to cycle through your data. You can print the names of every student in the school or search for a specific ID number by simply iterating through the array indices.

Key takeaway

An array of structures allows you to store a collection of complex data objects under a single name, accessible via an index.