使用#pramga pack()
设置字节对齐时不要将该语句放置在QCoreApplication
头文件前,否则调用QString
等类时将导致程序崩溃
//#pragma pack(push)
//#pragma pack(1) // QCoreApplication前修改字节对齐方式将导致程序崩溃
#include <QCoreApplication>
#pragma pack(push) // 保存原来的字节对齐方式
#pragma pack(1) // 设置1字节对齐
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication w(argc, argv);
struct TestStruct1
{
char c1;
short s;
char c2;
int i;
TestStruct1(){
c1 = 'a',
s = 0,
c2 = 'b',
i = 1;
}
};
struct TestStruct1 a;
qDebug()<< QString("c1:%1, s:%2,c2:%3, i:%4 ")
.arg(offsetof(TestStruct1,c1))
.arg(offsetof(TestStruct1,s))
.arg(offsetof(TestStruct1,c2))
.arg(offsetof(TestStruct1,i));
qDebug() << sizeof(a);
#pragma pack(pop) // 恢复字节对齐方式
return w.exec();
}