🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Free C Programming Course · Structure and Union
Array of Structures in C
Store many records in a table, initialise and loop over it, compute element counts safely, and place constant tables in flash.
What You Will Learn
- How to declare and initialise an array of structures
- How to access members with subscript plus dot notation
- How to count elements with the sizeof idiom
- How to search, swap and sort records
Prerequisites
- One-dimensional arrays
- Structure basics, assignment and padding (previous lectures)
- Basic pointers and the arrow operator
Array of Structures in C
An array of structures in C is how you store many records of the same kind: a table of ADC channels, a list of students, a set of timer jobs. A single structure describes one record. An array of that structure gives you a numbered list of them, stored side by side in memory. This lecture of our free C tutorial for embedded programmers shows how to declare, initialise, loop over and search such an array, and how to compute its size without hard-coding numbers.
Declaring an Array of Structures
First define the structure type, then declare an array of it exactly like an array of int:
struct channel adc[3];
Each element adc[0], adc[1], adc[2] is a full struct channel. You reach a member by combining a subscript with the dot operator: adc[1].raw. Read it left to right. The subscript selects the element, then the dot selects the member of that element.
All elements are stored one after another with no gaps between elements. Any padding lives inside each element (as you saw in the padding lecture), and every element has the same size, so the address of adc[i] is the array start plus i * sizeof(struct channel).
Initialising an Array of Structures
Use one pair of braces for the array and one pair per element. Inner braces are technically optional when every value is supplied in order, but keeping them makes the data readable and protects you if you later add a member. Leave the array length empty and let the compiler count the elements.
A Complete Example: ADC Channel Table
The program below keeps three analog channels in a table, converts each raw reading into a scaled value, finds the largest one and prints size information using the safe element-count idiom.
#include <stdio.h>
#include <stddef.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
struct channel {
const char *name;
int raw;
float gain;
};
static float scaled(const struct channel *c)
{
return (float)c->raw * c->gain;
}
int main(void)
{
struct channel adc[] = {
{ "VBAT", 2048, 0.002f },
{ "TEMP", 1500, 0.05f },
{ "LIGHT", 300, 0.1f },
};
size_t i;
size_t best = 0;
for (i = 0; i < ARRAY_SIZE(adc); i++) {
printf("%-5s raw=%4d scaled=%7.2f\n", adc[i].name, adc[i].raw, scaled(&adc[i]));
if (scaled(&adc[i]) > scaled(&adc[best]))
best = i;
}
printf("largest: %s\n", adc[best].name);
printf("elements = %zu, element size = %zu, total = %zu\n",
ARRAY_SIZE(adc), sizeof adc[0], sizeof adc);
printf("gap between adc[0] and adc[1] = %td bytes\n",
(char *)&adc[1] - (char *)&adc[0]);
return 0;
}
gcc -std=c11 -Wall -Wextra -o d1 d1.c
./d1
Expected output (sizes shown for a 64-bit PC; on a 32-bit Cortex-M the element size is 12):
VBAT raw=2048 scaled= 4.10
TEMP raw=1500 scaled= 75.00
LIGHT raw= 300 scaled= 30.00
largest: TEMP
elements = 3, element size = 16, total = 48
gap between adc[0] and adc[1] = 16 bytes
What to Notice
ARRAY_SIZE(a)divides the total size by the size of one element. Add a fourth channel to the table and every loop adjusts by itself.- The helper
scaledtakes aconst struct channel *, so the table is not copied for each call. We pass&adc[i], the address of one element. Inside the function the arrow operatorc->rawmeans the same as(*c).raw. - The distance between two neighbouring elements equals
sizeof adc[0], confirming the contiguous layout from the diagram. - The
namemember is aconst char *pointing to a string literal. It occupies pointer-size bytes inside the structure, not the characters themselves.
printf and scanf to save flash. If your output shows blank values or the linker complains, enable float formatting in your toolchain settings (with newlib-nano this is the -u _printf_float linker option for printing). On a desktop compiler you do not need anything extra.Looping, Searching and Sorting Records
Because the elements are ordinary objects, everything you learned about arrays still applies. A linear search compares one member against a key and returns the index. For a table that is sorted by a member, binary search works too. You can sort an array of structures with the bubble or insertion sort you wrote earlier, with one change: swap whole elements using a temporary structure, which uses the assignment rule from the first lecture of this chapter.
struct channel tmp = adc[i];
adc[i] = adc[j];
adc[j] = tmp;
Three lines swap complete records, whatever their size. Sorting a large table this way moves many bytes, so for big records sort an array of indices or pointers instead.
Real-World Use Cases
| Use case | What each element holds | Why an array of structures fits |
|---|---|---|
| Peripheral configuration table | Pin number, mode, pull setting | Initialise all pins with one loop |
| Command parser | Command text and handler function pointer | Look up a command by scanning the table |
| Task or timer list | Period, countdown, callback | A scheduler walks the list every tick |
| Data logger | Timestamp and reading | Fixed-size records, easy to store and send |
| Look-up tables in flash | Threshold and output value | Declare static const so the table stays in flash instead of RAM |
Common Mistakes and Troubleshooting
| Mistake | Result | Fix |
|---|---|---|
Writing sizeof(adc) / 3 | Breaks when the table grows | Use the ARRAY_SIZE idiom |
Using ARRAY_SIZE on a pointer parameter | Gives pointer size divided by element size, a wrong count | Pass the element count as a separate argument |
| Reading index equal to the length | Out of bounds read, undefined behaviour | Loop while i < count |
| Forgetting the dot after the subscript | Compile error: not a structure member access | Write adc[i].raw |
| Leaving a constant table writable | Uses RAM on a microcontroller | Declare it static const |
Best Practices and Performance
- Keep one table per concept and name it clearly, for example
adc_channels. - Use designated initialisers such as
{ .name = "VBAT", .raw = 0 }when a structure has many members; they survive member reordering. - Pass pointers to elements, not copies, when elements are large.
- Sequential access over contiguous records is cache friendly; scanning a table is usually faster than you expect.
Walking the Table with a Pointer
Subscripts are not the only way through a table. A pointer to a structure can step from the first element to one past the last, and the arrow operator reaches the members. This style produces compact loops and is common in driver code. The next program is a command table: each element holds a command name and a function to run, and a dispatcher scans the table for a matching word. It is exactly the structure of a simple UART shell.
#include <stdio.h>
#include <string.h>
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
struct command {
const char *name;
void (*run)(void);
};
static void cmd_start(void) { puts("motor started"); }
static void cmd_stop(void) { puts("motor stopped"); }
static void cmd_status(void){ puts("status: idle"); }
static const struct command table[] = {
{ "start", cmd_start },
{ "stop", cmd_stop },
{ "status", cmd_status },
};
static int dispatch(const char *word)
{
const struct command *c;
for (c = table; c < table + ARRAY_SIZE(table); c++) {
if (strcmp(c->name, word) == 0) {
c->run();
return 0;
}
}
return -1;
}
int main(void)
{
const char *inputs[] = { "start", "status", "reset", "stop" };
size_t i;
for (i = 0; i < ARRAY_SIZE(inputs); i++)
if (dispatch(inputs[i]) != 0)
printf("unknown command: %s\n", inputs[i]);
return 0;
}
gcc -std=c11 -Wall -Wextra -o h1 h1.c
./h1
motor started
status: idle
unknown command: reset
motor stopped
Study how c++ moves by one whole element, not one byte, because the pointer has type const struct command *. The loop stops at table + ARRAY_SIZE(table), the address one past the last element, which C allows for comparison. Adding a new command means adding one line to the table and one function; the dispatcher never changes. The table is static const, so on a microcontroller it normally lives in flash and uses no RAM.
Choosing Between Index and Pointer Loops
| Style | Strength | Watch out for |
|---|---|---|
Index loop for (i = 0; i < n; i++) | Easy to read, gives you the position | Signed and unsigned mix-ups with size_t |
Pointer loop for (p = tbl; p < tbl + n; p++) | Compact, no multiplication in source | Never dereference the end pointer |
One more habit worth building: keep the table and the code that uses it close together, and give the table a descriptive name. When a new engineer joins the project, a well-named table of structures is the fastest documentation of what the firmware can do. It also makes reviews easy, because adding a feature shows up as one new row instead of scattered edits across the program.
Key Takeaways
- An array of structures is a contiguous list of identical records.
- Use
arr[i].memberto access a field. sizeof(arr) / sizeof(arr[0])gives the count, but only where the array itself is in scope.- Swap whole records through a temporary structure.
- Declare read-only tables
static constto keep them in flash.
Frequently Asked Questions
How do I declare an array of structures in C?
Define the structure type first, then write struct type name array_name[N];. Each element is a complete structure.
How do I access a member of an array element?
Combine the subscript and the dot operator, for example adc[2].raw.
How can I find how many elements an array of structures has?
Divide the total size by the size of one element: sizeof(arr) / sizeof(arr[0]). This works only where the array itself is visible, not on a pointer parameter.
Are the elements of an array of structures stored contiguously?
Yes. Elements are consecutive in memory, and any padding is inside each element.
Can I initialise an array of structures at the declaration?
Yes, with nested braces. You may omit the array length and let the compiler count the initialisers.
How do I keep a table of structures in flash instead of RAM?
Declare it static const. On most embedded toolchains the table is then placed in read-only memory.
Keep Learning C for Embedded Systems
This lecture is part of our free embedded C programming course. Practice every program on your own machine, then move on to the next lecture.

2 Comments