31 January 2015

C sizeof structure member

Something I don’t think I’ve run into with C before.

It can be so hard to come up with a sensible example. So just ignore whether you think I should be doing this. Assume that something similar made sense in context.

typedef struct Foo {
    char uuid[37];
    int value;
} Foo;

char main_foo_uuid[sizeof(Foo.uuid)] = "";
//Compile error!

Doing sizeof(Foo) is fine, but sizeof(Foo.uuid) is not.

One solution is do declare a dummy instance of Foo.

Foo dummy;
char main_foo_uuid[sizeof(dummy.uuid)] = "";
//Works!

But there’s a trick to avoid declaring the dummy: Cast NULL to a pointer to Foo, and use that as your dummy.

char main_foo_uuid[sizeof(((Foo*)NULL)->uuid)] = "";
//Works!

Which makes you wonder why the language couldn’t just support sizeof(Foo.uuid).

No comments: