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

Combining array indexing and member access

Combining array indexing and member access

What you'll learn: How to navigate through a list of structured items by using the array index operator [] followed by the dot operator . to reach specific data fields.

The Digital Filing Cabinet

Imagine you have a row of physical filing cabinets. Each drawer represents an index in an array. However, inside each drawer, there isn't just one piece of paper; there is a specific folder containing a name, an ID number, and a phone number.

To find a specific person's phone number, you first have to pull out the correct drawer (the array index) and then look at the specific line on the form inside (the member access). In C, we do this by combining two symbols you already know: the square brackets [] and the dot ..

Syntactic Order

When working with an array of structures, the order of operations is crucial. You must tell C which structure you are talking about before you can ask for a member inside it.

struct Student {
    int id;
    float grade;
};

// Create an array of 3 Student structures
struct Student classroom[3] = {
    {101, 88.5},
    {102, 92.0},
    {103, 79.5}
};

// Access the grade of the second student (index 1)
float secondGrade = classroom[1].grade;

In the example above, classroom[1] identifies the entire structure sitting at index 1. Once that specific structure is "selected," we use .grade to drill down into the floating-point value stored there.

Common Pitfalls

It is easy to get the symbols backwards if you aren't careful. You cannot write classroom.grade[1], because classroom is the name of the entire array, and the array itself doesn't have a member named "grade"—only the individual structures inside it do.

Think of it like a street address: you must find the house number first (the index) before you can walk through the front door to find the kitchen (the member). If you try to walk into the "kitchen" of the entire street, you’ll just end up with a compiler error!

Key takeaway

Access a specific member within an array of structures by using the format arrayName[index].memberName.