【问题标题】:Unable to remove the structure padding completely - Codeblocks: Cygwin无法完全删除结构填充 - 代码块:Cygwin
【发布时间】:2018-03-11 15:48:05
【问题描述】:

结构“item_header”的大小,根据元素的大小应该是 512 字节,计算为 520 字节(使用 sizeof)。

我尝试删除填充,但只能将大小降低到 516 字节。

我发现删除填充的两个步骤是:

#pragma pack(push,1)         :-  This step reduced the size by 4 bytes
__attribute__ ((packed))     :-  This step had no effect on the structure size

如何将大小从 516 减小到 512?

编辑 1:结构声明:

struct item_header {
    char    history[256];   /* processing history */
    char    params[128];    /* special processing parameters */
    int32   processdate;    /* processing date */
    int32   datatype;       /* data type: speech, lx, etc */
    int32   subtype;        /* data sub-type: natural, synthetic, etc */
    int32   floating;       /* fixed or floating data */
    int32   datasize;       /* data item size (bytes) */
    int32   framesize;      /* no. items in time frame */
    int32   numframes;      /* no. frames in data */
    int32   length;         /* overall length (bytes) */
    char    comment[20];    /* data set comment */
    int32   windowsize;     /* size of analysis window in samples */
    int32   overlap;        /* size of analysis overlap in samples */
    int32   lxsync;         /* flag :larynx syncronous=1,fixed frame=0 */
    int32   lastposn;       /* last frame position */
    char    spare[40];      /* space for expansion */
    int32   machine;        /* machine code: 0=68000, 1=8086 */
    int32   datapresent;    /* data present 1=yes,0=no */
    double  frameduration;  /* time interval duration (s) */
    double  offset;         /* cumulative time offset */
}

【问题讨论】:

  • 重新排列结构以便不需要填充?如果不知道结构 以及它包含什么,或者结构应该用于什么,那么真的很难为您提供帮助。
  • 一个答案——我意识到这可能不是你正在寻找的答案——如果你试图删除填充的原因是你可以得到准确的结构匹配一些外部强加的布局(可能是文件格式或网络协议),从长远来看,一次解压一个字段的数据通常更容易和更便携。尝试正确定义结构,以便您可以使用fread 一次阅读所有内容并神奇地正确,这很有吸引力,但很难做到正确,正如您所发现的那样。 (然后是字节顺序...)
  • 如果您想得到这个问题的答案,而不是猜测或推测,您需要将完整的结构声明添加到您的问题中。
  • 你在这个结构中有指针吗?你用的是整数吗?根据架构,指针和整数可以有不同的大小。如需帮助,请提供源结构和目标结构。
  • @SteveSummit 是的,我正在尝试将结构与库规定的布局相匹配。代码处理输入文件的结构大小必须正好为 512 字节。

标签: c++ c data-structures


【解决方案1】:

256 字节:

char    history[256];

128 字节:

char    params[128];

8 * 4 字节 = 32 字节:

int32   processdate;
int32   datatype;
int32   subtype;
int32   floating;
int32   datasize;
int32   framesize;
int32   numframes;
int32   length;

20 字节:

char    comment[20];

4 * 4 字节 = 16 字节:

int32   windowsize;
int32   overlap;
int32   lxsync;
int32   lastposn;

40 字节:

char    spare[40];

2 * 4 字节 = 8 字节:

int32   machine;
int32   datapresent;

2 * 8 字节 = 16 字节:

double  frameduration;
double  offset;

256 + 128 + 32 + 20 + 16 + 40 + 8 + 16 = 总共 516 个字节

您的字段过多或某些内容超出了所需的范围(或者您所依赖的文档有误,或者...)。

【讨论】:

  • 感谢您的指出。结构声明取自库。文档(指定 512 字节大小)中没有 int32 变量之一。
猜你喜欢
  • 2018-05-01
  • 2021-05-21
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 2021-06-19
  • 2012-08-07
  • 2012-01-24
相关资源
最近更新 更多