【发布时间】:2019-03-28 22:48:27
【问题描述】:
我最近不得不处理结构中的位域,并且遇到了我无法解释的行为。
下面的struct应该是9个字节,根据各自的sizeof。但是对主结构执行 sizeof 会产生 10 个字节。
以下程序产生“10; 1 1 2 1 2 1 1 =9”
int main(){
struct{
uint8_t doubleoscillator;
struct{
char monophonic : 1;
char hold : 1;
char padding : 6;
} test;
int16_t osc1_multisound; //int
int8_t osc1_octave; // -2..1
int16_t osc2_multisound; //int
int8_t osc2_octave; // -2..1
int8_t intervall;
}osc;
std::cout << sizeof(osc) << "; ";
int a[7];
a[0] = sizeof(osc.doubleoscillator);
a[1] = sizeof(osc.test);
a[2] = sizeof(osc.osc1_multisound);
a[3] = sizeof(osc.osc1_octave);
a[4] = sizeof(osc.osc2_multisound);
a[5] = sizeof(osc.osc2_octave);
a[6] = sizeof(osc.intervall);
int total = 0;
for(int i=0;i<7;i++){
std::cout << a[i] << " ";
total += a[i];
}
std::cout << " = " << total << std::endl;
return 0;
}
为什么结构体内部变量的单个 sizeof() 和 osc 结构体的 sizeof() 产生的结果不同?
【问题讨论】:
-
因为编译器正在填充以对齐成员。
-
不应该已经对齐了吗?位域总和为 8 位
-
具体来说,
osc1_octave和osc2_multisound之间有一个字节的填充。 -
与您的位域无关。它与您在两个
int16_t之间添加了一个int8_t有关 -
未对齐的访问要么根本不起作用,要么效率低于对齐的访问,具体取决于处理器。典型行为是在 16 位边界上对齐 16 位值。有
#pragmas 和/或attributes 可以改变这种行为。 Here's an example of the latter.
标签: c++ struct bit-fields