c - C 中结构体的大小

标签 c memory struct

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/

相关文章:

c - 如何在c编程中再次显示预留的电影院座位

c - 如何用C实现一个简单的telnet客户端向服务器发送命令

c++ - C++ 编译器如何优化堆栈分配?

struct - 在 Julia 中实现相互嵌套结构的问题

c - 是否保证解析为 "(a ? b : (c ? d : e))"?

c++ - 二维对象数组内存问题 C++

c++ - 可以禁用 "Application Error"对话框吗?

c - 为什么递增指针可以工作,但将其视为数组会失败?第2部分

c - 创建房间的结构,然后将每个房间写入各自的唯一文件

c++ - 如何在QCoreApplication析构函数中删除对象和线程实例