1、测试代码
#include <QCoreApplication>
#pragma pack(push, 1)
typedef struct
{
int a;
float b;
char c;
int *d;
}testStruct;
#pragma pack(pop)
#include <QByteArray>
#include <QDebug>
int main()
{
testStruct structA;
structA.a = 1;
structA.b = 2;
structA.c = 'a';
structA.d = new int[10];
for (int i = 0; i < 10; ++i) {
structA.d[i] = i;
}
QByteArray arr;
arr.resize(49);
memcpy(arr.data(), &structA, 9);
memcpy(arr.data() + 9, structA.d, 40);
// testStruct *sb = reinterpret_cast<testStruct *>(arr.data());
testStruct *sb = (testStruct*)arr.data();
sb->d = reinterpret_cast<int *>(arr.data() + 9);;
for (int i = 0; i < 10; ++i) {
qDebug() << sb->d[i];
}
return 0;
}
2、输出结果
40642209
0
2
3
4
5
6
7
8
9
3、发现
经过调试指针转换后,发现本来设置的1字节对其变成了4字节对齐
QBytearray的data()指针被转换后会按照4字节自动对齐填充,不知为何会这样
>