<分区>
如标题所示,我想从该成员之前的其他成员获取 union 成员的偏移量(以字节为单位)(使用 offsetof
中定义的 stddef.h
宏)。这适用于预期的结构
#include <stdio.h>
#include <stddef.h>
struct bio {
int age;
char name;
};
int main( void ) {
printf("%d\n", offsetof(struct bio, name)); // result is 4 , which is what i expected
}
但对于 union 它打印 0
#include <stdio.h>
#include <stddef.h>
union bio {
int age;
char name;
};
int main( void ) {
printf("%d\n", offsetof(union bio, name)); // 0
}
只是一个后续问题,这种行为的原因是因为 union 的成员存储在同一个内存块中?
作为这个解释的一部分 wikipedia offsetof我还希望得到 4 而不是 0 的值