|
|
楼主 |
发表于 2023-5-20 17:12:38
|
显示全部楼层
记得结构是按里面最大的成员类型大小来对齐的。
你可以用 __attribute__((packed, aligned(X))) 来指定按多少字节对齐,比如
- struct {
- ...
- }__attribute__((packed, aligned(4)))
复制代码
就是按4字节对齐。
- struct {
- ...
- } __attribute__ ((packed))
复制代码
就是按实际大小,紧凑排列。
如果结构体用了 __attribute__ ((packed 这种属性,在高版本 GCC 上取结构体成员的地址就会报警,比如
- struct aaa {
- int a;
- } __attribute__ ((packed));
- int tmp = 2;
- struct aaa test;
- test.a = 1; // OK
- memcpy(&test.a, &tmp, sizeof(int)); // GCC 报警 taking address of packed member XXX may result in an unaligned pointer value
复制代码 |
|