Software That Lasts
Arrays & Structs
13 minStudent plan
Handling many values at once, grouping related data, and the memory limits that bite on a microcontroller.
After this lesson you can
- Use an array without running off the end
- Group related values into a struct
- Judge whether something will fit in 2 kB of RAM
Arrays
An array is a run of values of the same type stored consecutively, reached by index.
int readings[10]; readings[0] = 512;
Indices start at zero, so an array of ten has valid indices 0 to 9. Writing readings[10] is off the end, and C++ will not stop you. It writes over whatever memory happens to be next, and the resulting fault appears somewhere completely unrelated. This is the single most common cause of a sketch behaving bizarrely on hardware while looking correct on screen.
Arrays pair naturally with for loops, since the loop variable is the index. Averaging ten sensor readings is one loop and one division.
In the full lesson
- Arrays
- Structs
- Memory is small
This lesson comes with the Student plan. The first module of Programming is free.