Codiqo

Learn C · lesson 38 of 60 · about 8 minutes

Arrays of Structs

List the machine's services: keep many records in an array of structs, and loop over them to search and summarise.

What you'll learn

  • Declare an array of structs
  • Loop over records
  • Find a record that matches

The services

Four services run on the machine, or are meant to: sshd, backupd, webapp and cron. Each one has a name, the memory it uses and whether it's running, so each is a struct Service, and all four sit in one array. A loop counts the ones that are running and keeps the index of the biggest of those. Then the admin types a service's name, and a second loop with strcmp finds its row.

A table of records

An array of structs is like a table: each item is a row, each member a column. team[1].name is the name in row 1.

A leaderboard

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

struct Entry {
    char name[16];
    int xp;
};

int main(void) {
    struct Entry board[] = {{"Ada", 340}, {"Bo", 120}, {"Cy", 275}};
    int n = sizeof(board) / sizeof(board[0]);

    int best = 0;
    for (int i = 1; i < n; i++) {
        if (board[i].xp > board[best].xp) best = i;
    }
    printf("Top: %s with %d XP\n", board[best].name, board[best].xp);

    for (int i = 0; i < n; i++) {
        if (strcmp(board[i].name, "Bo") == 0) {
            printf("Bo is in row %d\n", i);
        }
    }
    return 0;
}

Output

Top: Ada with 340 XP
Bo is in row 1

Tip

Keep the index of the best row (best = i) rather than copying the whole struct each time. It's cheaper and you still know where it is.

Changing a row

board[i].xp += 50 changes the member in the array itself, because board[i] is the row, not a copy of it. A loop can update every row the same way.

A bonus for everyone

#include <stdio.h>

struct Entry {
    char name[16];
    int xp;
};

int main(void) {
    struct Entry board[] = {{"Ada", 340}, {"Bo", 120}};
    for (int i = 0; i < 2; i++) {
        board[i].xp += 50;
    }
    printf("%s %d, %s %d\n", board[0].name, board[0].xp, board[1].name, board[1].xp);
    return 0;
}

Output

Ada 390, Bo 170

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.