结构体内存

 

 

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个字节数

 



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值