C: member to drive up structure size up to a value

56 Views Asked by At

I have a structure that looks like this:

struct myStructure
{
    int index1;
    int index2;
    void *buffer;
    char fillData[];
};

I want to make the fillData member as big as it needs to make the structure an arbitrary size (512 bytes). I know I can calculate by hand and write that down but,to make this easily extensible in the future, I want it to scale up or down if needed automatically. Is there a way to achieve this automatic behaviour only using the preprocessor?

1

There are 1 best solutions below

3
mch On BEST ANSWER

offsetof cannot be used, because it needs the fully definition of the struct to work: https://godbolt.org/z/brEhThhe7

But you can put everything before the fillData into a struct and use sizeof on it:

struct myStructure
{
    struct inner {
        int index1;
        int index2;
        void *buffer;
    } inner;
    char fillData[WHOLE_SIZE - sizeof(struct inner)];
};

https://godbolt.org/z/zacxG1xrh

Using sizeof on all members might not work because of padding.