Preface:我对结构对齐进行了研究。看着this https://stackoverflow.com/questions/5435841/memory-alignment-in-c-structs问题,this https://stackoverflow.com/questions/4306186/structure-padding-and-packing一且还this https://stackoverflow.com/questions/5397447/struct-padding-in-c一个 - 但仍然没有找到我的答案。
我的实际问题:
这是我为了澄清我的问题而创建的代码片段:
#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
one.
简单的说:为什么不是sizeof(IntFloatAndDoubleStruct) = 24
?
提前致谢!
p.s:我正在使用 Visual-Studio 2017,标准控制台应用程序。
编辑:
根据评论,经过测试IntDoubleAndFloatStruct
(元素的不同顺序)并得到 24sizeof()
- 如果答案也能注意到并解释这个案例,我会很高兴。