我有这个代码
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
使它们成为完美的形状