ste*_*eve 1 c++ structure sizeof
变量v的大小为12个字节,但由于它的大小为6位,为什么它不是4个字节?
#include <iostream>
using namespace std;
struct abc {
int c : 4;
char x : 1;
int y : 1;
} v;
int main()
{
cout << sizeof v; // it prints 12 . why?
}
Run Code Online (Sandbox Code Playgroud)
问题是你混合了位字段的类型.这可能导致编译器添加填充以确保数据对齐.如果你int全部使用,那么成员之间不需要填充.
请注意,这取决于很多关于它的编译器所使用.如果我在家用Linux系统上使用GCC 6.2.0进行尝试,那么无论类型如何,我都会得到4个字节的大小.