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

hib*_*lem 4 c++

我有这个代码

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

Student s;
Run Code Online (Sandbox Code Playgroud)

现在我必须得到sizeof s

所以我补充道

printf("%d",sizeof(s));
Run Code Online (Sandbox Code Playgroud)

现在,当我点击编译时,结果显示为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           |

+-------+-------+-------+
Run Code Online (Sandbox Code Playgroud)

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 willpad''结构中(好像有额外的,不可见的字段),如下所示:

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

|           a           | pad1  |

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

|       b       |     pad2      |

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

|               c               |

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

|           d           | pad3  |

+-------+-------+-------+-------+
Run Code Online (Sandbox Code Playgroud)

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

48 + 152

4 + 196

200 + 0

1 + 199

使它们成为完美的形状

Jam*_*lis 16

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

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