cunionsmemory-layout

Union between an array and a struct of arrays. Can memory layout be tested at comptime?


While experimenting with the C language, I realized that I could "name" my matrix dimensions using a union.

typedef union {
    float a[2][10];
    struct {
        float a_0[10];
        float a_1[10];
    };
} Matrix_t;

void main(void) {
    Matrix_t foo = {.a[1][5] = 42.0f};

    assert(42.0f == foo.a_1[5]); // it works !
}

I know that struct and union can be padded depending on the architecture, but I'm unsure of their interaction when used together with arrays.

Is there a way to guarantee at compile-time that the memory layout will be valid? (I'm open to using gcc/clang extension if need be)

Maybe something like this?

_Static_assert(sizeof((Matrix_t){0})==sizeof(float[2][10]));

Solution

  • The offsetof macro can be used:

    #include <assert.h>
    #include <stddef.h> // for offsetof
    
    typedef union {
        float a[2][10];
        struct {
            float a_0[10];
            float a_1[10];
        };
    } Matrix_t;
    
    _Static_assert(offsetof( Matrix_t, a[1][5] ) == offsetof( Matrix_t, a_1[5] ));
    
    int main()
    {
    }