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.
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
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.
#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 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?
Chaining dot operators reaches a field nested inside another struct field.