结构体的大小,内有对齐



#include <stdio.h>
struct A
{
 int a;
 int b;
};   //最后求得的字节数是8
struct B
{
 char a;
 int b;
};   //最后求得的字节数也是8(因为它浪费了三个字节而提升了速度)
struct C
{
 char a;   //1+1  //由于1不是2的倍数,所以要加1
 short b;   //2   //由于2+1+1是4的倍数所以此处2不用再加
 int c;   //4 
};   //最后求得的字节数是 4+2+1+1=8

struct D   //【内存对齐】
{
 char a;
 char x;   //保留不使用
 short b;
 int c;
};   //最后求得的字节数一直是8

struct E
{
 short a;   //2+2
 int b;   //4
 long long *c ;   //4  //看*  因为是指针所以是4
};   //最后求得的字节数是2+2+4+4=12

struct F
{
 char a;   //1+3
 int b;   //4
 short c;   //2 
};   //本来最后求得的字节数是 1+3+4+2=10,(但是因为10不是4的倍数,所以需要10+2=12)
//【需要最后求得的字节数是单个最大的成员的倍数 所以本题是12而不是10】
//(用图中的解释是因为结构体还可以定义数组(当定义数组时,蓝色部分可以解决但是绿色部分的红线处解决不了))

struct G
{
 int a;  //4
 struct HH
 {
  char b;  //1+3
  int c;  // 4
 };
};   //最后求得的字节数是12
struct H
{
 int a;  //4+4
 int b;  //8
};   //最后求得的字节数是4+4+8=16

int main()
{
 printf("%d\n",sizeof(struct A));
 return 0;
}




猜你喜欢

转载自blog.csdn.net/bian1cheng1/article/details/80287615