C语言__attribute__(packed)属性

在公司实习的时候,看到了这个属性的应用,做个总结:

其实很简单:程序中没有__attribute__(packed),优化对齐,一般是4字节对齐,的话,紧凑型,不对齐,是多少就是多少。上代码:

#include<stdio.h>
struct unpacked_str{
char c;
int x;
};
struct packed_str{
char c;
int x;
}__attribute__((packed));
int main()
{
    printf("size of char=%d\n",sizeof(char));
    printf("size of int=%d\n",sizeof(int));
    printf("size of unpacked_str=%d\n",sizeof(struct unpacked_str));
    printf("size of packed_str=%d\n",sizeof(struct packed_str));
}

在codeblocks 17.12中运行结果如下:

但结果差强人意,第二个应该是5的,不知道是不是和编译器有关,这是我用的编译器。

是不是编译器的问题还需要确认,如果后续我得到了正确答案,我会更博的。

 

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值