struct A
{
int a;//4
int b;//4
};//4+4
结构体A占用内存为8字节
struct B
{
char a;//1+3
int b;//4
};1+3+4
结构体B占用内存为8,char类型占用字节数为1,但要保证前一个字节数是后一个字节数倍数,所以需要在char类型后+3
+3的原因:
虽然在a后面浪费了3个内存,但是104可以整除4,108可以整除2,这样子会使得计算机的运行速度加快,浪费的内存数对于计算机而言是很少很少的一部分。
struct F
{
char a;//1+3
int b;//4
short c;//2
};//10+2 //内存要满足是最大字节数的倍数 //10不是4的倍数,所以应该+2
结构体F的内存是12 //10+2
+2的原因
在没有+2之前,114不可以整除4
在+2之后,浪费的2个字节数在c之后,在这个时候的116可以整除4,同样是浪费2个字节数,用来换取运行速度的提高。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct A
{
int a;//4
int b;//4
};//4+4
struct B
{
char a;//1+3
int b;//4
};
struct C
{
char a;//1+1
short b;//2
int c;//4
};//8
struct D
{
char a;//1+3
int b;//4
int c;//4+4
double d;//8
};
struct E
{
short a;//2+2
int b;//4
long long *c;//4
};
struct F
{
char a;//1+3
int b;//4
short c;//2
};//10+2 //内存要满足是最大字节数的倍数 //10不是4的倍数,所以应该+2
struct G//不需要考虑对齐的应用
{
char a;
char x;//保留,不使用
short b;
int c;
};
struct H
{
int a;
struct HH//12
{
char b;//12,13~15
int c;//16
}d;
};//12
struct I
{
int a;//8
double b;//12
};//16
int main()
{
printf("%d\n",sizeof(struct A));
printf("%d\n",sizeof(struct B));
printf("%d\n",sizeof(struct C));
printf("%d\n",sizeof(struct D));
printf("%d\n",sizeof(struct E));
printf("%d\n",sizeof(struct F));
printf("%d\n",sizeof(struct G));
printf("%d\n",sizeof(struct H));
printf("%d\n",sizeof(struct I));
return 0;
}
!注意:指针只占用4个字节数