C语言中结构体struct怎么对齐

这篇文章主要介绍“C语言中结构体struct怎么对齐”,在日常操作中,相信很多人在C语言中结构体struct怎么对齐问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C语言中结构体struct怎么对齐”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

专注于为中小企业提供网站设计、成都做网站服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业屏南免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了1000+企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。

struct,相互关联的元素的集合,每个元素都有自己的内存空间;每个元素在内存中的存放是有先后顺序的,就是定义时候的顺序;一个struct所占的总的内存大小,并不是各个元素所占空间之和,而是存在字节对齐的问题.
struct中的每个元素相对于结构体的首地址的偏移量能被该元素的size整除(某些编译器,如果该元素的size > 4,则偏移量能被4整除即可).
测试代码:

[xdb@localhost test]$ cat test.cpp
#include <cstdio>
#include <iostream>
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]$

到此,关于“C语言中结构体struct怎么对齐”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注创新互联网站,小编会继续努力为大家带来更多实用的文章!

文章名称:C语言中结构体struct怎么对齐
地址分享:https://www.cdcxhl.com/article36/pihhpg.html

成都网站建设公司_创新互联,为您提供手机网站建设自适应网站网站排名搜索引擎优化微信公众号

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

外贸网站制作