我编写了这段代码来优化要对齐数组的结构:
#include <iostream>
#include <stdlib.h>
struct Foo {
int z;
char c;
} __attribute__((packed));
struct FooForArray
{
Foo f;
char aligner[sizeof(int)-sizeof(Foo)%sizeof(int)]; // fill the missing bytes with this dump array for aligment
};
int main()
{
std::cout<<"sizeof AlignedFoo = "<<sizeof(FooForArray)<<std::endl;
std::cout<<"sizeof Foo = "<<sizeof(Foo)<<std::endl;
system("pause");
}
输出:
sizeof AlignedFoo = 8
sizeof Foo = 5
Press any key to continue...
我认为大多数编译器默认会这样做,但我这样做是为了学习,这是一个好方法吗?