64,636
社区成员
发帖
与我相关
我的任务
分享
struct A
#include <iostream>
using namespace std;
struct C
{
char a;
short c;
long b;
};
int main()
{
cout << sizeof(struct C) << endl;
return 0;
}
//结果就不同鸟,char(1), 空, short(2), long (4)
//有点递归的味道在里面
struct A
{
char a;
char b;
char b;
};
//都是char,都是1字节的,所以向1对齐,大小为1 * 3 = 3
struct B
{
short a;
short b;
short c;
};
//都是short,都是2字节的,所以向2对齐,大小为2 * 3 = 6
struct C
{
char a;
long b;
short c;
};
//长度分别为1, 4 ,2 ,所以向4对齐,大小为4 * 3 = 12
//也可以加入预编译指令,强制向1对齐
#include <iostream>
using namespace std;
#pragma pack(push, 1)
struct C
{
char a;
long b;
short c;
};
#pragma pack(pop)
int main()
{
cout << sizeof(struct C) << endl;
return 0;
}
//结果为7