【发布时间】:2018-11-21 18:01:30
【问题描述】:
前言: 我对结构对齐进行了研究。看了this 问题,this 一个和this 一个 - 但仍然没有找到我的答案。
我的实际问题:
这是我创建的代码 sn-p 以澄清我的问题:
#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,标准控制台应用程序。
编辑:
每个 cmets,测试 IntDoubleAndFloatStruct(元素的不同顺序)并在 sizeof() 中得到 24 个 - 如果答案也能说明并解释这种情况,我会很高兴。
【问题讨论】:
-
切换float和double的顺序,你应该得到24。
-
你为什么期望得到 24 个?如果没有
double,您对int和float有什么期望,为什么? -
@Gerhardh - 换了顺序,得到了 24!至于我的期望,我期望与最大元素对齐 - 所以 8 字节 * 3 个元素 = 24。Int 和 Float 具有相同的大小 (4),所以 8 就可以了 IMO。
-
我喜欢你研究过的链接列表,而不是仅仅写“我阅读了所有内容”。就像许多其他问题一样。干得好。