Home / Learn Embedded C / Nested Structs and Arrays of Structs

Nested Structs and Arrays of Structs

Structs inside structs, and arrays that hold many structs at once.

The short versionStructs inside structs, and arrays that hold many structs at once.

Theory in plain words

Definition

A struct field can itself be another struct ("nesting"), and you can declare an array of structs, just like an array of ints, to hold many records of the same shape.

Why you need this

A device with several sensors naturally wants an array of Reading structs; a configuration struct often nests smaller structs (like a Pin struct inside a Device struct).

How it works

Nested fields are accessed by chaining dots (device.pin.number); array-of-struct elements are accessed with the usual index then a dot (readings[2].value).

Where you'll see this

  • Sensor logs
  • Configuration tables
  • Device descriptors

Try it

The same log, as two parallel arraysC: edit and run

An array of structs keeps the id and value for each entry together in one place instead of two separate arrays that have to stay in sync by hand.

Careful:As in the previous lesson, this course's sandbox does not execute struct code, so the array-of-structs listing below is reference-only. The runnable "Try it" box uses two parallel arrays instead, which is exactly what an array of structs is doing underneath.
An array of sensor readings (reference only — not runnable in this sandbox)
#include <stdio.h>
struct Reading { int sensor_id; int value; };
int main() {
    struct Reading log[3] = {
        {1, 512}, {2, 480}, {3, 500}
    };
    for (int i = 0; i < 3; i++) {
        printf("sensor %d = %d\n", log[i].sensor_id, log[i].value);
    }
    return 0;
}

Try it: a nested field, as separate variables

A nested device.pin.number field, as separate variablesC: edit and run

A real nested struct would reach these same two values as device.pin.number and device.pin.mode.

Test what you just read

1. How do you access the "number" field of a Pin struct nested inside a Device struct, via a Device variable called dev?