0

考虑 C11 中的以下类型,其中 MyType1 和 MyType2 是先前声明的类型:

typedef struct {
  int tag;
  union {
    MyType1 type1;
    MyType2 type2;
  }
} MyStruct;

我想分配足够的内存malloc来保存tag属性和type1. 这可以通过便携式方式完成吗?我想,sizeof(tag) + sizeof(type1)由于对齐问题,可能无法正常工作。

我可以以可移植的方式从结构的开头计算 type1 的偏移量吗?

4

2 回答 2

3

您可以使用offsetof(),因为这将包括大小tag和任何填充,然后添加大小就足够了type1

void *mys = malloc(offsetof(MyStruct, type1) + sizeof (MyType1));
于 2015-01-16T10:20:00.597 回答
1

我可以以可移植的方式从结构的开头计算 type1 的偏移量吗?

您可能可以使用offsetoffrom stddef.h

printf("Offset of type1 in the struct: %zu\n", offsetof(MyStruct, type1));

旁注:这是因为您使用的是“匿名联合”。如果你说union { ... } u; type1不会是MyStruct.

于 2015-01-16T10:17:54.737 回答