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;

 

相关文章:

  • 2021-11-16
  • 2022-12-23
  • 2021-12-09
  • 2021-10-28
猜你喜欢
  • 2022-12-23
  • 2021-07-26
  • 2023-04-05
  • 2022-12-23
  • 2022-12-23
  • 2022-01-29
  • 2022-12-23
相关资源
相似解决方案