jz2440裸机开发与分析:串口编程4之struct内存占用介绍

由于在x86(32位机器)平台下,GCC编译器默认按4字节对齐,
如:结构体4字节对齐,即结构体成员变量所在的内存地址是4的整数倍。

可以通过使用gcc中的__attribute__选项来设置指定的对齐大小。

1):
attribute ((packed)),让所作用的结构体取消在编译过程中的优化对齐,
按照实际占用字节数进行对齐。

2):
__attribute((aligned (n))),让所作用的结构体成员对齐在n字节边界上。
如果结构体中有成员变量的字节长度大于n,
则按照最大成员变量的字节长度来对齐。
代码如下:

struct  person{
	char *name;
	int  age;
	char score;
	int  id;
};

struct  person1{
	char *name;
	int  age;
	char score;
	int  id;
}__attribute__ ((packed));

struct  person2{
	char *name;
	int  age;
	char score;
	int  id;
}__attribute((aligned (4)));

int main(int argc,char **argv)
{
	struct  person per={"www.100ask.org",10,'A',123};
	printf("sizeof(char   )=%d\n",sizeof(char   ));
	printf("sizeof(int    )=%d\n",sizeof(int    ));
	printf("sizeof(char  *)=%d\n",sizeof(char  *));
	printf("sizeof(char **)=%d\n",sizeof(char **));	
	printf("sizeof(struct  person)=%d\n",sizeof(struct  person));
	printf("sizeof(struct  person1)=%d\n",sizeof(struct  person1));
	printf("sizeof(struct  person2)=%d\n",sizeof(struct  person2));	

	printf("&per.name  =%p,per.name  =%s\n",&per.name ,per.name);
	printf("&per.age   =%p,per.age   =%d\n",&per.age  ,per.age);	
	printf("&per.score =%p,per.score =%d\n",&per.score,per.score);		
	printf("&per.id    =%p,per.id    =%d\n",&per.id   ,per.id);			
	return 0;
}

结果为:

sizeof(char   )=1
sizeof(int    )=4
sizeof(char  *)=4
sizeof(char **)=4
sizeof(struct  person)=16
sizeof(struct  person1)=13
sizeof(struct  person2)=16
&per.name  =0xbfe6bf60,per.name  =www.100ask.org
&per.age   =0xbfe6bf64,per.age   =10
&per.score =0xbfe6bf68,per.score =65
&per.id    =0xbfe6bf6c,per.id    =123
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值