前言:
我的研究结构对齐.看了 this问题,this一个和 this一个 – 但仍然没有找到我的答案.
我的研究结构对齐.看了 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 – 如果答案会注意并解释这个案例,我将很高兴.
解决方法
你的结构必须是8 * N字节长,因为它有一个8字节(双)的成员.这意味着结构位于存储器中的地址(A)可被8整除(A%8 == 0),其结束地址将是(A 8N),也可以被8整除.
从那里,您存储2个4字节变量(int float),这意味着您现在占用内存区域[A,A 8].现在存储一个8字节的变量(双精度).因为(A 8)%8 == 0 [因为A%8 == 0],所以不需要填充.因此,没有填充,你得到4 4 8 == 16.
如果您将订单更改为int – >双 – >浮动你将占用24个字节,因为双变量原始地址不能被8整除,并且它必须填充4个字节才能到达有效地址(并且结构在末尾也会有填充).
- |--------||--------||--------||--------||--------||--------||--------||--------|
- | each || cell || here ||represen||-ts 4 || bytes || || |
- |--------||--------||--------||--------||--------||--------||--------||--------|
- A A+4 A+8 A+12 A+16 A+20 A+24 [addresses]
- |--------||--------||--------||--------||--------||--------||--------||--------|
- | int || float || double || double || || || || | [content - basic case]
- |--------||--------||--------||--------||--------||--------||--------||--------|
- first padding to ensure the double sits on address that is divisble by 8
- last padding to ensure the struct size is divisble by the largest member's size (8)
- |--------||--------||--------||--------||--------||--------||--------||--------|
- | int || padding|| double || double || float || padding|| || | [content - change order case]
- |--------||--------||--------||--------||--------||--------||--------||--------|