C - Arrays of structures

Overview

Arrays of structs let you manage collections of related records.

Learning Objectives

  • Declare arrays of structs and iterate over them.

Prerequisites

Example

#include <stdio.h>

typedef struct { char name[32]; int age; } Person;

int main(void) {
  Person people[3] = { {"Ann",30}, {"Ben",25}, {"Cat",28} };
  for (int i = 0; i < 3; i++) {
    printf("%s (%d)\n", people[i].name, people[i].age);
  }
}

Checks for Understanding

  1. How do you access the age of the second element?
Show answer

people[1].age

Expected Output

Ann (30)
Ben (25)
Cat (28)

Practical Example: Find Oldest

#include <stdio.h>

typedef struct { char name[32]; int age; } Person;

const Person* oldest(const Person *arr, int n) {
  if (n <= 0) return NULL;
  int idx = 0;
  for (int i = 1; i < n; i++) if (arr[i].age > arr[idx].age) idx = i;
  return &arr[idx];
}

Usage Output (sample):

Oldest: Ann (30)

Common Pitfalls

  • Be careful with array bounds while iterating.
  • Copying structs is by value; consider pointers if you store references.
  • When storing strings in fixed-size char arrays, guard against overflow.

Exercises

  1. Sort an array of Person by age ascending using qsort.
  2. Filter an array to print only people older than a given threshold.