Possible Duplicate:
What is the actual size of a struct in C
我用 C 语言编写了以下程序,我对可执行文件打印的结构的大小有点困惑。这是代码:
#include <stdio.h>
#include <stdlib.h>
struct domi1{
char x;
int c;
char y;
};
struct domi2{
char x;
char y;
int c;
};
main(){
printf("The size of domi1 is: %d\n", sizeof(struct domi1));
printf("The size of domi2 is: %d\n\n", sizeof(struct domi2));
system("pause");
}
程序打印 12 作为 domi1 的大小,8 作为 domi2 的大小。这是为什么?感谢您的帮助!
最佳答案
因为Packing and byte alignment
一般的答案是编译器可以自由地在成员之间添加填充以实现对齐目的。或者我们可以说,您可能有一个编译器将所有内容都对齐到 8 字节。
第一个结构分配内存为- 4 4 4
第二个结构 - 单 4 两个 char
4 代表 int
关于c - C 中结构体的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12989342/