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?
>Solution :
offsetof looks like a standard macro: https://man7.org/linux/man-pages/man3/offsetof.3.html
Therefore, the following should work everywhere:
struct myStructure
{
int index1;
int index2;
void *buffer;
char fillData[WHOLE_SIZE - offsetof(struct myStructure, fillData)];
};
if you do not want to use offsetof, 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/jKxfEP89v
Using sizeof on all members might not work because of padding.