C结构尺寸不一致 [英] C struct sizes inconsistence

查看:121
本文介绍了C结构尺寸不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  如何找到一个结构的大小?结果
  结构在内存大小?

我使用下面的结构进行网络通信,它创造了很多不必要的字节之间。

I am using following struct for network communication, It creates lots of unnecessary bytes in between.

它提供了不同大小比预期的8个字节。

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;

和它给出了一个大小为8,代替7。
我再加上一个领域,它仍然给出了同样的尺寸

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;


可有人请上解决此问题的帮助?

更新:我需要在传输数据包来保存的格式,所以我想跳过这些垫

UPDATE: I need the format to hold while transmitting the packet, So I want to skip these paddings

推荐答案

听说过对齐和填充的?

基本上,以确保快速访问某些类型必须对内存地址的某些界限。结果
这就是所谓的对齐方式。

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结构尺寸不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆