cstatic-initialization

How to initialize an global array to a struct?


Sorry for the bad title, but I don't know how else to phrase why I'm trying to do.

In C, how can I initialize a global array of bytes with a different type? That is, I'm trying to do this:

#define HEAP_SIZE   2048U

struct memblock
{
    uint16_t prev;
    uint16_t next;
    uint16_t size;
    uint16_t magic;
};

static uint8_t heap[HEAP_SIZE] = (struct memblock)
{
    .prev = 0,
    .next = 0,
    .size = HEAP_SIZE - sizeof(struct memblock),
    .magic = 0,
};

That is, I have a 2048-byte buffer called "heap", and I want to initialize the first 8 bytes according to the layout of memblock. I know I can write a function to do that, but I want to avoid having to write a function that has to be called in order to initialize this global variable.


Solution

  • You can do this with a union, although then it requires using the union name to access the array:

    static union
    {
        uint8_t         heap[HEAP_SIZE];
        struct memblock m;
    } u = { .m = {
            .prev = 0,
            .next = 0,
            .size = HEAP_SIZE - sizeof (struct memblock),
            .magic = 0,
        } };
    

    The array would be referred to as u.heap, or you could use a preprocessor macro to conceal the union.

    Kludges like this are generally ill advised and should be avoided without good reason.