三步解决C语言中struct字节对齐问题,C语言中结构体struct的对齐问题

#include using namespace std;

#define LL long long

struct E1 {

int a; char b; char c;

}e1;

struct E2 {

char b; int a; char c;

}e2;

struct E3 {

char a; short b; int c; LL d;

}e3;

struct E4 {

int c; LL d; char a; short b;

}e4;

struct E5 {

char a1,a2,a3,a4,a5,a6;

}e5;

struct E6 {

char a1,a2,a3;

}e6;

struct E7 {

struct E5 elem5;

struct E6 elem6;

LL a;

}e7;

struct E8 {

char a[9];

}e8;

struct E9 {

struct E8 elem8;

LL a;

}e9;

struct E10 {

char a;

};

int main() {

puts("----> E1");

cout << sizeof(E1) << endl;

printf("%x %x %x %x\n", &e1, &e1.a, &e1.b, &e1.c);

puts("----> E2");

cout << sizeof(E2) << endl;

printf("%x %x %x %x\n", &e2, &e2.b, &e2.a, &e2.c);

puts("----> E3");

cout << sizeof(E3) << endl;

printf("%x %x %x %x %x\n", &e3, &e3.a, &e3.b, &e3.c, &e3.d);

puts("----> E4");

cout << sizeof(E4) << endl;

printf("%x %x %x %x %x\n", &e4, &e4.c, &e4.d, &e4.a, &e4.b);

puts("----> E5");

cout << sizeof(E5) << endl;

puts("----> E6");

cout << sizeof(E6) << endl;

puts("----> E7");

cout << sizeof(E7) << endl;

printf("%x %x %x %x\n", &e7, &e7.elem5, &e7.elem6, &e7.a);

puts("----> E8");

cout << sizeof(E8) << endl;

puts("----> E9");

cout << sizeof(E9) << endl;

printf("%x %x %x\n", &e9, &e9.elem8, &e9.a);

puts("----> E10");

cout << sizeof(E10) << endl;

return 0;

}

[xdb@localhost test]$

```

编译,执行

```

[xdb@localhost test]$ g++ test.cpp -o test

[xdb@localhost test]$ ./test

----> E1

8

6021a0 6021a0 6021a4 6021a5

----> E2

12

6021a8 6021a8 6021ac 6021b0

----> E3

16

6021c0 6021c0 6021c2 6021c4 6021c8

----> E4

24

6021d0 6021d0 6021d8 6021e0 6021e2

----> E5

6

----> E6

3

----> E7

24

602200 602200 602206 602210

----> E8

9

----> E9

24

602230 602230 602240

----> E10

1

[xdb@localhost test]$

```

**参考资料**

[struct的字节对齐](http://www.gonglin91.com/cpp-struct-union/)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值