structof中的sizeof

Woo*_*ung 1 c int struct sizeof

 #include <stdio.h>
 #include <string.h>
 #include <malloc.h>

struct Student {
       char name[100];
       int id;
       char major[50];
       char address[200];
};

int main()
{

     struct Student st;

     strcpy(st.name, "Chuck");
     st.id = 20001;
     strcpy(st.major, "Computer Science");
     strcpy(st.address, "1st Street");

     printf("%d %d %d %d %d\n", sizeof(st), sizeof(st.name),sizeof(st.id), sizeof(st.major), sizeof(st.address));

     return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出为356 100 4 50 200.为什么sizeof(st)356,而不是354?我尝试了这个没有int,输出是350 100 50 200,所以我假设问题在整数.

NPE*_*NPE 7

这是由于struct成员之间的填充.填充是确保每个数据成员在内存中正确对齐所必需的.确切的对齐要求取决于您的架构.

因此,您不能假设a的大小struct等于其成员大小的总和.