繁体   English   中英

为什么sizeof会给我这个结果?

[英]Why is sizeof giving me this result?

我有这个代码

struct Student {
char name[48];
float grade;
int marks[10,5];
char gender;
};

Student s;

现在我必须得到sizeof s

所以我补充道

printf("%d",sizeof(s));

现在,当我点击编译时,结果显示为256

这是错误的,因为它应该是253

因为大小

char name [48]; ----> 48

浮动等级; -----> 4

int标记[10,5]; ------> 200

char性别; -------> 1

所以48 + 4 + 200 + 1 = 253

那为什么告诉我256?

================================

这部分是在我看到你的答案后写的

我了解到了

假设我有这个结构:struct {char a [3]; short int b; long int c; char d [3]; };

那么......

+-------+-------+-------+

|           a           |

+-------+-------+-------+

|       b       |

+-------+-------+-------+-------+

|               c               |

+-------+-------+-------+-------+

|           d           |

+-------+-------+-------+

packed'' version, notice how it's at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it's hard for the processor, too. Therefore, most compilers will packed'' version, notice how it's at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it's hard for the processor, too. Therefore, most compilers will packed'' version, notice how it's at least a little bit hard for you and me to see how the b and c fields wrap around? In a nutshell, it's hard for the processor, too. Therefore, most compilers will填充''结构(好像有额外的,不可见的字段),如下所示:

+-------+-------+-------+-------+

|           a           | pad1  |

+-------+-------+-------+-------+

|       b       |     pad2      |

+-------+-------+-------+-------+

|               c               |

+-------+-------+-------+-------+

|           d           | pad3  |

+-------+-------+-------+-------+

所以如果Im的最大尺寸是200,那么填充应该是这样的

48 + 152

4 + 196

200 + 0

1 + 199

使它们成为完美的形状

结构的成员之间或结构的末尾可能存在填充字节。

在这种情况下,可能在结构的末尾有三个字节的填充,在单个char成员之后,以确保结构的大小是四的倍数。

编译器将结构填充以与字边界对齐。 处理器处理256字节的块比处理253的奇数更容易。

int marks[10,5];

应该

int marks[10][5];

可能还存在填充和对齐问题。

如果使用Visual C ++,请将#pragma pack(1)添加到源文件的顶部以消除struct padding。 VC ++的默认值是8字节边界。

gcc和其他编译器将有自己的等价物。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM