在C结构的大小 [英] Size of a structure in C

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

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member\">Why ISN&rsquo的;?吨的sizeof为等于每个成员的sizeof的总和一个struct

考虑下面的C code:

Consider the following C code:

#include <stdio.h>    

struct employee
{
  int id;
  char name[30];  
};

int main()
{
  struct employee e1;      
  printf("%d %d %d", sizeof(e1.id), sizeof(e1.name), sizeof(e1));
  return(0);
}

输出是:

4月30日36

为什么是结构体的大小不等于其个别成分变量的大小的总和

Why is the size of the structure not equal to the sum of the sizes of its individual component variables?

推荐答案

编译器可能对对齐要求增加填充。注意,这不仅适用于一个结构的场间填充,但也可以适用于该结构的端部(使结构类型的阵列将具有各元件正确地对准)。

The compiler may add padding for alignment requirements. Note that this applies not only to padding between the fields of a struct, but also may apply to the end of the struct (so that arrays of the structure type will have each element properly aligned).

例如:

struct foo_t {
    int x;
    char c;
};

虽然 C 字段不需要填充,该结构一般有一个的sizeof(结构foo_t)== 8 (32位系统上 - 而是一个带有32位 INT 键入系统),因为将需要3个字节填充后的<$ ç$ C> C 字段。

Even though the c field doesn't need padding, the struct will generally have a sizeof(struct foo_t) == 8 (on a 32-bit system - rather a system with a 32-bit int type) because there will need to be 3 bytes of padding after the c field.

注意填充可能不是由系统(如86或Cortex M3)要求,但是编译器可能仍然添加它性能方面的原因。

Note that the padding might not be required by the system (like x86 or Cortex M3) but compilers might still add it for performance reasons.

这篇关于在C结构的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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