Question

I would like to combine a struct and a byte array in a union. The compiler is gcc.

Is the following considered good/save code for a 32bit embedded controller (AVR)? Do I have to worry about the byte aligment?

#include <stdint.h>

typedef int8_t S8;

typedef union {
    struct {
        S8 a;
        S8 b;
        S8 c;
        S8 d;
        S8 e;
    };
    S8 array[5];
} s_t;

Initialization:

s_t s = {.array = {0, 0, 0, 0, 0}};

Access:

s.a = 50;
s.c = 42;
Was it helpful?

Solution

I think what you're showing is fine, but you should be worried if you ever use an array of s_t as there might be padding at the end.

You can tell GCC to "pack" the struct using the extension __attribute__ syntax. Add __attribute__((packed)) before the final ;.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top