C/C++:#pragma pack(1)

对齐规则:
每 个 变 量 相 对 起 始 位 置 的 偏 移 量 必 须 是 该 变 量 类 型 大 小 的 整 数 倍 ! {\red{每个变量相对起始位置的偏移量必须是该变量类型大小的整数倍!}}

对于union,CPU默认按最短成员对齐:

union u{
    double a;
    int b;
};
union u1{
    char a[13];
    int b;
};
union u2{
    char a[13];
    char b;
};
int main(){
    cout<<sizeof(u)<<endl;
    cout<<sizeof(u1)<<endl;
    cout<<sizeof(u2)<<endl;
    return 0;
}

输 出 : {\orange{输出:}} : 8 16 13

union成员共享内存,并以最小成员对齐,不足补齐,故union可以用来判断CPU大小端。

对于struct,按规则对齐,最后大小必须是最大成员的整数倍:

struct s{
    char c;
    short s1;
    short s2;
    int i;
};
struct s1{
    char c;
    int i;
};
struct s2{
    char c;
    short s1;
    int i;
};
struct s3{
    char c;
    int i;
    short s1;
};
int main(){
    cout<<sizeof(s)<<endl;
    cout<<sizeof(s1)<<endl;
    cout<<sizeof(s2)<<endl;
    cout<<sizeof(s3)<<endl;
    return 0;
}

o u t p u t : {\orange{output:}} output: 12 8 8 12

p r a g m a   p a c k {\red{pragma\ pack}} pragma pack 修改CPU对齐方式

#pragma pack(1)

struct s{
    char c;
    short s1;
    short s2;
    int i;
};
struct s1{
    char c;
    int i;
};
struct s2{
    char c;
    short s1;
    int i;
};
struct s3{
    char c;
    int i;
    short s1;
};
int main(){
    cout<<sizeof(s)<<endl;
    cout<<sizeof(s1)<<endl;
    cout<<sizeof(s2)<<endl;
    cout<<sizeof(s3)<<endl;
    return 0;
}

O u t p u t : {\orange{Output:}} Output: 9 5 7 7


规则:

pragma(n),n必须是1,2,4,8,若不是则按默认


内存对齐的意义:

  • 对齐后性能可以提升。

  • 方便平台移植

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值