C中结构的大小 [英] size of struct in C
问题描述
可能的重复:
为什么不是’t sizeof for struct 等于每个成员的 sizeof 之和?
考虑以下 C 代码:
#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(struct foo_t) == 8
(在 32 位系统上 -而是具有 32 位 int
类型的系统),因为在 c
字段之后需要 3 个字节的填充.
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.
请注意,系统(如 x86 或 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屋!