C中结构的大小

时间:2012-10-20 14:21:29

标签: c memory struct

  

可能重复:
  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的大小。这是为什么?感谢您的帮助!

1 个答案:

答案 0 :(得分:-1)

因为Packing and byte alignment
一般的答案是编译器可以自由地在成员之间添加填充以便进行对齐。或者我们可以说,你可能有一个编译器将所有内容对齐到8个字节。 第一个结构分配内存as- 4 4 4
charint

的第二个结构单4