C Workshop · Array of Structs
Lesson C

Array of Structs

A class is an array of Student. Index then dot: class[1].marks.

What it is

A class is a row of Student records. Index first, then the field: class[1].marks is “the second student’s score.” Arrays of structs are how tables live in memory.

Approach

  1. Declare struct Student class[2].
  2. Fill each element's fields.
  3. Print class[1].marks.

Where this is used in the real world

Diagram

1

[0] 70

first

2

[1] 80

second

3

class[1].marks

80

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2struct Student {
3    int id;
4    int marks;
5};
6int main(void) {
7    struct Student c[2];
8    c[0].id = 1; c[0].marks = 70;
9    c[1].id = 2; c[1].marks = 80;
10    printf("%d\n", c[1].marks);
11    return 0;
12}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. c[1].marks is:

Second student.

2. Index of the first student is:

Zero-based array.

3. c[1] is:

One struct.

4. To print every marks column you would:

Loop + dot.

5. This is different from int marks[2] because:

Several fields per row.