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

Searching through struct arrays

Searching through struct arrays

What you'll learn: How to locate specific records in a collection of data by combining loops with structure member access.

Finding the needle in the haystack

Imagine you have a physical filing cabinet full of employee folders. Each folder (a struct) contains a name and an ID number. If you need to find "Alice," you don't just grab a random handful of papers; you start at the first folder, check the name, and move to the next until you find a match.

In C, searching an array of structures works exactly like this manual filing process. Because an array of structures is just a list of custom data packets, we use a for loop to visit each index and the dot operator (.) to peek inside the specific member we are looking for.

The search pattern

To search, we typically iterate through the array and use an if statement to compare our target value against the struct member at the current index. If we find a match, we can save that index or perform an action immediately.

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

struct Student {
    int id;
    char name[20];
};

int main() {
    // An array of 3 Student structures
    struct Student classList[3] = {
        {101, "Bob"},
        {102, "Alice"},
        {103, "Charlie"}
    };

    int searchTarget = 102;
    int foundIndex = -1; // -1 means "not found"

    // The Search Loop
    for (int i = 0; i < 3; i++) {
        if (classList[i].id == searchTarget) {
            foundIndex = i;
            break; // Stop looking once we find it
        }
    }

    if (foundIndex != -1) {
        printf("Student found: %s\n", classList[foundIndex].name);
    } else {
        printf("Student ID not found.\n");
    }

    return 0;
}

Why this matters

When you access classList[i].id, you are telling C: "Go to the ii-th folder in the cabinet, open it, and look at the ID written inside."

Note the use of the break statement. Just like in real life, once you find the folder you need, there is no reason to keep looking through the rest of the cabinet. This makes your code more efficient, especially if your "filing cabinet" contains thousands of records.

When searching for strings instead of integers, remember to use strcmp() from the <string.h> library rather than ==, but the logic of looping through the array remains identical.

Key takeaway

To search a struct array, loop through the indices and use the dot operator to compare the target value against a specific member of each element.