Home / Learn Embedded C / Structs in C
Structs in C
Grouping related fields (like a sensor reading's id, value and timestamp) into one named type.
How to think about this
What it is
A struct groups several related variables ("fields") of possibly different types under one name, accessed with the dot (.) operator.
Why it matters
A sensor reading naturally has several related pieces of data (an id, a value, a timestamp) — a struct keeps them together as one unit instead of juggling three separate arrays.
Mechanically speaking
The compiler lays out each field one after another in memory (subject to padding, covered in the Memory group); you access a field with structname.fieldname.
Shows up in
- Sensor readings
- Register definitions
- Protocol packets
Try it
A struct groups exactly these three variables under one name — same data, tidier to pass around as a unit.
#include <stdio.h>
struct Reading {
int sensor_id;
int value;
int timestamp_ms;
};
int main() {
struct Reading r;
r.sensor_id = 3;
r.value = 512;
r.timestamp_ms = 10200;
printf("sensor %d read %d at %d ms\n", r.sensor_id, r.value, r.timestamp_ms);
return 0;
}Try it: a pin configuration, as two plain variables
A struct PinConfig with "number" and "mode" fields would group these same two plain variables under one name.
Check yourself
1. What operator accesses a field of a struct variable?
The dot operator accesses a field of a plain struct variable (-> is for accessing through a pointer, covered later).