【发布时间】:2025-12-01 23:35:01
【问题描述】:
我在 linux 上使用 c 中的结构。 我开始使用位字段和“打包”属性,但遇到了一个奇怪的行为:
struct __attribute__((packed)) {
int a:12;
int b:32;
int c:4;
} t1;
struct __attribute__((packed)) {
int a:12;
int b;
int c:4;
}t2;
void main()
{
printf("%d\n",sizeof(t1)); //output - 6
printf("%d\n",sizeof(t2)); //output - 7
}
为什么这两种结构 - 完全相同 - 占用不同的字节数?
【问题讨论】:
-
因为
t2::b保证是一个不同的内存位置?想想数据竞赛。
标签: c gcc struct bit-fields packed