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.

Quick summaryGrouping 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

The same reading, as three plain variablesC: edit and run

A struct groups exactly these three variables under one name — same data, tidier to pass around as a unit.

Tip:Structs are also exactly how this course (and real datasheets) model a hardware register block in C — covered in the Memory-Mapped I/O group.
Careful:This course's sandbox interpreter does not execute struct code (it is a known limitation of the small, educational C interpreter used here), so the listing below is a reference-only example — real C, just not runnable in this particular sandbox. The "Try it" box underneath shows the same idea using plain variables, which does run here.
Defining and using a sensor reading struct (reference only — not runnable in this sandbox)
#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 pin configuration, as two plain variablesC: edit and run

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?