为什么__int64在结构中占用12个字节

Why does __int64 take 12 bytes inside struct?

本文关键字:12个 字节 结构 int64 为什么      更新时间:2023-10-16

我有VC++2012,并注意到如果有类似的东西

struct mystruct{
     char a[100];
     __int64 b; };

那么sizeof(mystruct)将产生112。

为什么会这样?

必须添加填充。考虑:

mystruct *a = (mystrct *) malloc (16 * sizeof (mystruct));

如果没有填充,一些64位整数就不会对齐。

如果您需要特定二进制格式的数据,则必须编写代码以将该数据放入该二进制格式。不要试图通过偶然或魔术来做这件事。编写代码,精确地生成文件中所需的字节数。

为什么会这样?简短回答,记忆对齐。

答案很长:http://www.catb.org/esr/structure-packing/