Lesson 25 / 36

Arrays of Structures

Model a list of records, like rows in a table.

A table of students

Combine a struct with an array to store many records of the same shape.

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

struct Student class[3] = {
    {"Ana", 88},
    {"Bilal", 76},
    {"Chen", 92}
};

for (int i = 0; i < 3; i++) {
    printf("%s: %d\n", class[i].name, class[i].marks);
}

Output:

Ana: 88
Bilal: 76
Chen: 92

Pass by pointer to avoid copies

Passing a large struct (or array of structs) by value copies every byte. Pass a pointer (struct Student *s) to a function instead, and use s->field to access members.

Quick check: What does `s->field` mean when `s` is a pointer to a struct?

  • Shorthand for (*s).field
  • It compares s and field
  • It creates a new struct
Answer

Shorthand for (*s).field — `->` dereferences the pointer and accesses the member in one step.