Arrays of Structs

You can make an array of structs – a list of records, like a small database:

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

typedef struct {
    char name[20];
    int price;
} Item;

int main() {
    Item menu[3];
    strcpy(menu[0].name, "Tea");
    menu[0].price = 20;
    strcpy(menu[1].name, "Coffee");
    menu[1].price = 35;
    strcpy(menu[2].name, "Cake");
    menu[2].price = 50;

    for (int i = 0; i < 3; i++) {
        printf("%-8s %3d\n", menu[i].name, menu[i].price);
    }
    return 0;
}

Output

Tea       20
Coffee    35
Cake      50

menu[1].price means "the price of item number 1".

Reading records from input

#include <stdio.h>

typedef struct {
    char name[20];
    int score;
} Player;

int main() {
    int n;
    Player players[50];
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%s %d", players[i].name, &players[i].score);
    }

    int best = 0;
    for (int i = 1; i < n; i++) {
        if (players[i].score > players[best].score) {
            best = i;
        }
    }
    printf("Winner: %s with %d points\n", players[best].name, players[best].score);
    return 0;
}

Input (what the user types)

3
Anu 40
Ben 75
Cara 60

Output

Winner: Ben with 75 points

Tip: Instead of remembering the best score, we remember the index of the best player. Then we can print both their name and their score.

Common mistake: Forgetting & for number fields in scanf: it's &players[i].score, but players[i].name (a string) needs no &.

HOME LABS COMMUNITY DASHBOARD