zoukankan      html  css  js  c++  java
  • C/C++结构体内存对齐

    ZC: 注意点:
    ZC:  (1)、不同的编译器 对结构体(“struct”和“typedef struct”)的内存对齐 可能不同;
    ZC:  (2)、关键词“__packed”,网上查到 可以使用这个,但是我没有尝试成功,不知 如何使用...

    测试环境:Win7x64,cn_visual_studio_2010_ultimate_x86_dvd_532347.iso,qt-opensource-windows-x86-msvc2010_opengl-5.3.2.exe

    1、

     1.1、测试代码:

    #pragma pack (1)//指定按2字节对齐/
    
    struct struct01
    {
        int i;
        short us;
    };
    
    typedef struct
    {
        int i;
        short us;
    } struct02;
    
    struct struct03
    {
        short us;
        int i;
    };
    
    typedef struct
    {
        short us;
        int i;
    } struct04;
    #pragma pack ()//取消指定对齐,恢复缺省对齐/
    
    struct struct05
    {
        int i;
        short us;
    };
    
    typedef struct
    {
        int i;
        short us;
    } struct06;
    
    
    struct struct07
    {
        short us;
        int i;
    };
    
    typedef struct
    {
        short us;
        int i;
    } struct08;
    
    void MainWindow::on_pushButton_clicked()
    {
        qDebug() << "sizeof(struct01) : " << sizeof(struct01);
        qDebug() << "sizeof(struct02) : " << sizeof(struct02);
        qDebug() << "sizeof(struct03) : " << sizeof(struct03);
        qDebug() << "sizeof(struct04) : " << sizeof(struct04);
        qDebug() << "sizeof(struct05) : " << sizeof(struct05);
        qDebug() << "sizeof(struct06) : " << sizeof(struct06);
        qDebug() << "sizeof(struct07) : " << sizeof(struct07);
        qDebug() << "sizeof(struct08) : " << sizeof(struct08);
    }

     1.2、控制台输出:

    sizeof(struct01) :  6
    sizeof(struct02) :  6
    sizeof(struct03) :  6
    sizeof(struct04) :  6
    sizeof(struct05) :  8
    sizeof(struct06) :  8
    sizeof(struct07) :  8
    sizeof(struct08) :  8

    2、

    3、

  • 相关阅读:
    十天冲刺---Day10
    十天冲刺---Day9
    团队博客目录
    【Beta阶段】M2事后分析
    【Beta阶段】展示博客
    【Beta阶段】测试报告
    【Beta阶段】发布说明
    【Beta阶段】团队源代码管理
    【Beta阶段】第十次Scrum Meeting!!!
    【Beta阶段】第九次Scrum Meeting!(论坛已成功上线)
  • 原文地址:https://www.cnblogs.com/cppskill/p/6431970.html
Copyright © 2011-2022 走看看