C struct sizes inconsistence(C 结构体大小不一致)
问题描述
<块引用>可能的重复:
如何找到结构的大小?
Struct 的内存大小不同?
我正在使用以下结构进行网络通信,它在两者之间创建了许多不必要的字节.
它给出的大小与预期的 8 字节不同.
struct HttpPacket {无符号字符 x1;联合{结构{无符号字符长度;未签名的短主机;无符号字符内容[4];} 数据包;无符号字符字节[7];无符号长数;}
即使我从联合中删除一个字段,以下也会给出不同的大小
struct HttpPacket {无符号字符 x1;联合{结构{无符号字符长度;未签名的短主机;无符号字符内容[4];} 数据包;无符号长数;}
<小时>
另外,一个更清晰的例子
struct {无符号字符长度;未签名的短主机;无符号字符内容[4];} 数据包;
它给出的大小为 8,而不是 7.我再添加一个字段,它仍然给出相同的大小
struct {无符号字符 EXTRAADDEDFIELD;无符号字符长度;未签名的短主机;无符号字符内容[4];} 数据包;
<小时>
有人可以帮忙解决这个问题吗?
更新:我需要在传输数据包时保持格式,所以我想跳过这些填充
听说过对齐和填充吗?>
基本上,为了确保快速访问,某些类型必须在某些内存地址范围内.
这称为对齐.
为了实现这一点,允许编译器将字节插入到您的数据结构中以实现该对齐.
这称为填充.
Possible Duplicate:
How do I find the size of a struct?
Struct varies in memory size?
I am using following struct for network communication, It creates lots of unnecessary bytes in between.
It gives different size than expected 8 Bytes.
struct HttpPacket {
unsigned char x1;
union {
struct {
unsigned char len;
unsigned short host;
unsigned char content[4];
} packet;
unsigned char bytes[7];
unsigned long num;
}
And Following gives different size even though that I am removing a field from a union
struct HttpPacket {
unsigned char x1;
union {
struct {
unsigned char len;
unsigned short host;
unsigned char content[4];
} packet;
unsigned long num;
}
Also, A more clear example
struct {
unsigned char len;
unsigned short host;
unsigned char content[4];
} packet;
And it gives a size of 8, instead of 7. And I add one more field, It still gives the same size
struct {
unsigned char EXTRAADDEDFIELD;
unsigned char len;
unsigned short host;
unsigned char content[4];
} packet;
Can someone please help on resolving this issue ?
UPDATE: I need the format to hold while transmitting the packet, So I want to skip these paddings
Ever heard of alignment and padding?
Basically, to ensure fast access, certain types have to be on certain bounds of memory addresses.
This is called alignment.
To achieve that, the compiler is allowed to insert bytes into your data structure to achieve that alignment.
This is called padding.
这篇关于C 结构体大小不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C 结构体大小不一致
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01