Indexing into a struct array
What you'll learn: How to access and modify specific data fields within a list of structures using array notation.
The Digital Ledger
Think of a struct as a single row in a spreadsheet. If you have a Student struct, one row might hold a name, an ID number, and a GPA. An array of structures is the entire spreadsheet.
When you have a list of items, you need a way to point to exactly one "row" and then pick a specific "column" within that row. In C, we do this by combining the array index [] with the dot operator ..
Step-by-Step Access
To get information out of a struct array, you follow a two-step mental process:
- Identify the item: Use the index (e.g.,
students[2]) to pick which specific struct you want to talk to. - Identify the field: Use the dot operator (e.g.,
.gpa) to pick the variable inside that struct.
Crucially, the index always comes first. You are picking the "box" from the shelf before you look at what is inside it.
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
// Create an array of 3 Point structures
struct Point path[3] = { {0, 0}, {10, 20}, {50, 80} };
// Accessing data: Let's look at the second point (index 1)
printf("Second point coordinates: %d, %d\n", path[1].x, path[1].y);
// Modifying data: Let's move the third point (index 2)
path[2].x = 100;
path[2].y = 200;
return 0;
}
The Order of Operations
A common mistake is trying to put the index after the field name. Remember: path.x[2] would imply that the variable x is an array. Since path is the array, the brackets must stay attached to path.
When you write path[i].x, C evaluates path[i] first, which results in a single struct Point. Then, it looks inside that result for .x. This makes managing large collections of data—like a list of users, a set of coordinates, or an inventory of products—as simple as looping through a standard array.
Key takeaway
Use arrayName[index].member to reach inside a specific structure within an array.