Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading