C 结构体大小不一致

C struct sizes inconsistence(C 结构体大小不一致)

本文介绍了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 结构体大小不一致

基础教程推荐