前言: 我对结构体对齐做了研究。看过this这个问题,this还有this这个问题——但是仍然没有找到我的答案。
我的实际问题:
这里是我创建的代码片段,以澄清我的问题:
#include "stdafx.h"
#include <stdio.h>
struct IntAndCharStruct
{
int a;
char b;
};
struct IntAndDoubleStruct
{
int a;
double d;
};
struct IntFloatAndDoubleStruct
{
int a;
float c;
double d;
};
int main()
{
printf("Int: %d\n", sizeof(int));
printf("Float: %d\n", sizeof(float));
printf("Char: %d\n", sizeof(char));
printf("Double: %d\n", sizeof(double));
printf("IntAndCharStruct: %d\n", sizeof(IntAndCharStruct));
printf("IntAndDoubleStruct: %d\n", sizeof(IntAndDoubleStruct));
printf("IntFloatAndDoubleStruct: %d\n", sizeof(IntFloatAndDoubleStruct));
getchar();
}
它的输出是:
Int: 4
Float: 4
Char: 1
Double: 8
IntAndCharStruct: 8
IntAndDoubleStruct: 16
IntFloatAndDoubleStruct: 16
我理解了
IntAndCharStruct
和IntAndDoubleStruct
的对齐方式,但是我不理解IntFloatAndDoubleStruct
的对齐方式。简单来说:为什么
sizeof(IntFloatAndDoubleStruct) != 24
?谢谢! P.S:我在使用标准控制台应用程序,Visual-Studio 2017。 编辑: 根据评论,测试了
IntDoubleAndFloatStruct
(元素排序不同),并在sizeof()
中得到24,如果答案也能注意并解释这种情况,那将是很好的。
sizeof()
的正确格式说明符是"%zu"
。 - Andrew Henle