struct sizeof 结果不是预期的
我有一个这样定义的结构:
typedef struct _CONFIGURATION_DATA {
BYTE configurationIndicator;
ULONG32 baudRate;
BYTE stopBits;
BYTE parity;
BYTE wordLength;
BYTE flowControl;
BYTE padding;
} CONFIGURATION_DATA;
现在,根据我的计算,该结构有 10 个字节长。但是,sizeof 报告它的长度是 16 个字节?有人知道为什么吗?
我正在使用 Windows DDK 中的构建工具进行编译。
I have a a struct defined thusly:
typedef struct _CONFIGURATION_DATA {
BYTE configurationIndicator;
ULONG32 baudRate;
BYTE stopBits;
BYTE parity;
BYTE wordLength;
BYTE flowControl;
BYTE padding;
} CONFIGURATION_DATA;
Now, by my reckoning, that struct is 10 bytes long. However, sizeof reports that it is 16 bytes long? Anyone know why?
I am compiling using the build tools in the Windows DDK.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
结盟。
使用
#pragma pack(1)
...struct comes here...
#pragma pack()
我还建议重新排序,并且如果需要,则使用保留字节进行填充,以便多字节整数类型更好地对齐。这将使 CPU 的处理速度更快,并且代码更小。
Alignment.
use
#pragma pack(1)
...struct goes here...
#pragma pack()
I would also recommend reordering things, and if necessary padding then with RESERVED bytes, so that multi-byte integral types will be better aligned. This will make processing faster for tbe CPU, and your code smaller.
更改元素的顺序。从 ULONG 开始,然后是 BYTE。这将改善结构在内存中的对齐方式。
Change the order of the elements. Start with the ULONG, followed by the BYTEs. This will improve the struct's alignment in memory.
这是由于填充造成的,因为在您的平台上,
ULONG32
显然必须在 4 字节边界上对齐。由于struct
的开头和结尾显然也必须对齐,因此第一个和最后一个BYTE
将分别填充 3 个字节。This is due to padding, because on your platform, an
ULONG32
apparently must be aligned on 4-byte boundaries. Since the start and end of thestruct
apparently also must be aligned, the first and lastBYTE
will be padded with 3 bytes each.您测量的额外大小是编译器引入的填充。
据推测,您正在使用 32 位系统,因此在
configurationIndicator
和baudRate
之间将有 3 个字节的填充,并且在结构体末尾还有 3 个字节的填充。The extra size you are measuring is the padding introduced by the compiler.
Presumably, you are working on a 32 bits system, so you will have 3 bytes of padding between
configurationIndicator
andbaudRate
, and 3 more bytes of padding at the end of the struct.