What is a struct in C? Grouping data and mapping hardware registers
Atlasbot · 16/8/2026 · 11 min read
When you need to store a lot of related information — for example, data read from an IMU including acceleration, angular velocity, and temperature — declaring each discrete variable can be confusing. Struct solves exactly this problem: collects them into a single block, with a clear name and structure.
Key concepts
struct defines a new data type, consisting of many members of different types, accessed by name:
typedef struct {
float accel_x;
float accel_y;
float accel_z;
uint8_t temperature;
} ImuData;
ImuData imu;
imu.accel_x = 0.98f;
imu.temperature = 27;
The members of the struct are stored continuously in memory, in the correct order of declaration — this is an important detail, not just a neat organization of the code.
Padding — struct is not "as small as it seems"
Compilers often insert additional padding bytes between members so that each member is at an address divisible by its size (memory alignment), because it is faster for the CPU to read properly aligned data. As a result, sizeof(struct) can be larger than the total size of the members combined:
struct BadOrder {
uint8_t flag; // 1 byte + 3 byte padding
uint32_t timestamp; // 4 byte
uint8_t status; // 1 byte + 3 byte padding
}; // sizeof = 12 bytes, even though the actual data is only 6 bytes!
struct GoodOrder {
uint32_t timestamp; // 4 byte
uint8_t flag; // 1 byte
uint8_t status; // 1 byte + 2 byte padding
}; // sizeof = 8 bytes — more economical thanks to sorting from largest to smallest
In short: Sorting struct members from large to small types reduces wasteful padding — notable when RAM is only a few dozen KB and there are hundreds of instances of that struct.
How it works
The most important use of structs in embedded is to map the entire register block of a hardware peripheral into a struct, and then "force" a pointer to point to that peripheral's base address — each member of the struct then corresponds exactly to an actual register on the chip:
typedef struct {
volatile uint32_t MODER; // Pin mode (input/output)
volatile uint32_t ODR; // Output value
volatile uint32_t IDR; // Readable input value
} GPIO_TypeDef;
#define GPIOA ((GPIO_TypeDef *)0x40020000) // Base address of the GPIOA block
GPIOA->ODR |= (1 << 5); // Write directly to the actual ODR register on the chip
This is exactly how the STM32 HAL library works internally — each peripheral (GPIO, Timer, UART...) is described by such a struct, making the code easier to read (GPIOA->ODR) instead of having to remember and type each hex address by hand.
Technical details
Formulas
The alignment rule that the compiler follows: each member's address must be divisible by its own size (or the default alignment size of that type); The total size of the struct is rounded up to a multiple of the member with the largest alignment:
offset(member) is a multiple of sizeof(member)
sizeof(struct) is the multiple of the largest alignment among the members
Example: BadOrder above — uint32_t needs alignment 4
flag (offset 0, 1 byte) → needs 3 bytes of padding so timestamp starts at offset 4 (multiple of 4)
status (offset 8, 1 byte) → needs 3 bytes of padding so the total struct is a multiple of 4 → sizeof = 12
Parameters
Required alignment of common data types on most 32-bit microcontrollers:
| Type | Size | Alignment required |
|---|---|---|
uint8_t | 1 byte | 1 byte (not required) |
uint16_t | 2 byte | 2 byte |
uint32_t / float | 4 byte | 4 byte |
double | 8 byte | 8 bytes (some 32-bit MCUs only base 4 bytes) |
Register / Bit / Byte
The member declaration order in the register mapping struct must exactly match the actual offset order on the chip — this is not a cosmetic detail. For example on STM32, the real GPIO block has a fixed offset map: MODER at offset 0x00, OTYPER at 0x04, OSPEEDR at 0x08, PUPDR at offset 0x0C, IDR at 0x10, ODR in 0x14 — struct GPIO_TypeDef in the STM32 header file is declared correctly in this order so that GPIOA->ODR automatically points to the correct offset 0x14 from base address 0x40020000. Reversing the order of any two members in the struct will cause the read/write code to be completely mistaken to another register, even though the variable name is still correct.
Practical applications
Struct is often used as a fixed frame format when 2 boards communicate via UART/CAN in a multi-board robot system — For example, the motor control MCU packs the left/right wheel speed and battery status into a struct, sending that byte block via UART to the upper level MCU to read back the correct structure. This method is much faster and more compact than sending each individual eigenvalue with a separator — but requires both sides to compile the struct with the same member order and same padding (see note in the Common Errors section), otherwise the received data will be completely out of field even if the number of bytes transmitted is correct.
Practical example
#include <stdio.h>
#include <stdint.h>
#include <stddef.h> // cho offsetof()
struct BadOrder {
uint8_t flag;
uint32_t timestamp;
uint8_t status;
};
int main() {
printf("sizeof(BadOrder) = %zu\n", sizeof(struct BadOrder));
printf("offset flag = %zu\n", offsetof(struct BadOrder, flag));
printf("offset timestamp = %zu\n", offsetof(struct BadOrder, timestamp));
printf("offset status = %zu\n", offsetof(struct BadOrder, status));
return 0;
}
Output:
sizeof(BadOrder) = 12
offset flag = 0
offset timestamp = 4
offset status = 8
The result matches the formula in the Technical Knowledge section: timestamp (4 bytes, need align 4) cannot start at offset 1 immediately after flag, so the compiler inserts 3 bytes of padding to push it to offset 4 — as expected, not random behavior.
Common mistakes
- Reversing the order of members in the register mapping struct — as mentioned in the Register/Bit/Byte section, the wrong order causes the code to read/write to a completely different register, often causing confusing errors (GPIO pins do not react, or react to the wrong pin).
- Send the raw bytes of a struct directly via UART/CAN between two chips of different architectures — if the two sides have different padding or byte ordering (endianness), the received data will be out of field even if the total number of bytes is correct — the byte-by-byte format should be clearly defined instead of relying on how the compiler arranges the struct itself.
- Forgot
volatilefor register mapping struct — similar to the error mentioned in the Pointer article, missingvolatilecauses the compiler to skip reading/writing the actual value of the register. - Don't pay attention to padding when there are hundreds of instances of the struct — with only a few dozen KB of RAM, a struct with 4-6 bytes of extra padding multiplied by hundreds of records (eg: sensor history buffer) can uselessly take up dozens of extra KB of RAM.
Conclusion
Struct in C embedded has two parallel roles: neatly organizing related data for application code, and accurately describing the actual register map of the hardware when mapping directly. Understanding alignment/padding helps both save RAM and avoid mismapping register offsets. The next article in this category is about Array — a way to store multiple values of the same type continuously in memory, the foundation for sensor data buffers.
Get new articles and lessons by email
When a new technical article or course module is published, Atlas Robotics sends you a short email. No spam.
Unsubscribe any time with the link in each email. See our Privacy policy.