C语言中结构体大小计算

1.普通结构体

struct student 
{
char sex;
char a;
char b;
int age;
char name[100];
};
该结构体大小为108
解答:
1.先算struct的对齐大小,对齐的大小也是取决于struct成员中字节对齐最大的那个;在给的题目中就是int类型,也就是4byte。如果结构体成员小于4byte,需要补齐填满4byte
2、三个char类型虽然只有3byte,但是为了4byte对齐,也需要填充为4byte。所以总的大小就是(1+1+1=4)+4+100 = 108

2.结构体数组

 struct student{
        char name[10];
        int score;
 };
 struct student class[5];
 int length = sizeof(class);
 printf("结构体大小为%d\n",length); 
输出结果为80

解答:按照正常计算应该为(10+4)*5=70;但是这里需要考虑字节对齐的情况,所以按照int类型对齐,大小为80

3.结构体指针数组

 struct student{
     char name[10];
     int score;
 };
 struct student class[5];
 int length = sizeof(class);
 printf("结构体大小为%d\n",length); 
  输出结果为40

解答:不管结构体内的元素个数和大小,数组中每个元素所存放的都是指针地址,即为整数,占8个字节,所以大小为5*8=40;