Consider the following type in C11, where MyType1 and MyType2 are previously declared types:
typedef struct {
int tag;
union {
MyType1 type1;
MyType2 type2;
}
} MyStruct;
I'd like to allocate enough memory using malloc
to hold the tag
attribute and type1
. Can this be done in a portable way? I guess, sizeof(tag) + sizeof(type1)
may not work due to alignment issues.
Can I calculate the offset of type1 from the beginning of the structure in a portable way?
You can use offsetof()
, and since that will include both the size of tag
and any padding, it's enough to then add the size of type1
:
void *mys = malloc(offsetof(MyStruct, type1) + sizeof (MyType1));