为什么打包不能在同级联合或结构中起作用 [英] Why does packing not work across sibling unions or structs
问题描述
在下面的示例中,我希望 complex_t
的大小与 uint16_t
相同:2个字节,但是这是3个字节。
In the following example I expect the size of complex_t
to be the same as uint16_t
: 2 bytes, however it's 3 bytes.
删除第二个联合( proximity_unsafe)可将大小减小到2个字节,但我无法弄清楚打包规则的模型。
Removing the second union ("proximity_unsafe") reduces the size to 2 bytes, but I can't figure out the model of the packing rules.
#include <stdint.h>
#include <stdio.h>
typedef union {
uint16_t unsafe;
struct {
uint16_t backwardmotion_unsafe : 1;
uint16_t batteryvoltage_unsafe : 1;
union {
uint16_t dropoff_unsafe : 4;
struct {
uint16_t dropofffrontleft_unsafe : 1;
uint16_t dropofffrontright_unsafe : 1;
uint16_t dropoffsideleft_unsafe : 1;
uint16_t dropoffsideright_unsafe : 1;
}__attribute__((__packed__));
}__attribute__((__packed__));
union {
uint16_t proximity_unsafe : 3;
struct {
uint16_t proximityfront_unsafe : 1;
uint16_t proximityleft_unsafe : 1;
uint16_t proximityright_unsafe : 1;
}__attribute__((__packed__));
}__attribute__((__packed__));
} __attribute__((__packed__));
} __attribute__((__packed__)) complex_t;
int main()
{
printf("sizeof(complex_t): %i", sizeof(complex_t));
printf("sizeof(uint16_t): %i", sizeof(uint16_t));
}
推荐答案
因为合法服用不是位域的任何命名结构成员的地址,此类非位域成员必须从字节边界开始。尽管不可能获取匿名成员的地址,因此从理论上讲,编译器可以允许此类对象从任意位边界开始,但这将暗示结构的布局将根据其成员是否不同而有所不同。被命名。
Because it is legal to take the address of any named struct member that is not a bitfield, such non-bitfield members are required to start at byte boundaries. While it is not possible to take the address of anonymous members, and it would thus theoretically be possible for a compiler to allow such objects to start at arbitrary bit boundaries, that would imply that the layout of a structure would vary based upon whether its members were named.
这篇关于为什么打包不能在同级联合或结构中起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!