zoukankan      html  css  js  c++  java
  • C++高效编程笔记2:struct中的字节对齐

    #include <iostream.h>

    structA{
        chara;longb;charc;longd;
    };
    structB{
        chara;charc;longb;longd;
    };

    #pragma pack(push, 1)
    structC{
        chara;longb;charc;longd;
    };
    #pragma pack(pop)

    structD{
        char*a;char*b;
    };
    //使用比特域的结构
    structBitField{
        unsigneda1:11;  //long 1
        unsigneda2:11;
        unsignedb1:10;
        unsigneda3:11;  //long 2
        unsigneda4:11;
        unsignedb2:10;
    };

    voidmain(void)
    {
        cout<<"Size of A : "<<sizeof(A)<<"bytes"<<endl;
        cout<<"Size of B : "<<sizeof(B)<<"bytes"<<endl;
        cout<<"Size of C : "<<sizeof(C)<<"bytes"<<endl;
        cout<<"Size of D : "<<sizeof(D)<<"bytes"<<endl;
        cout<<"Size of BitField : "<<sizeof(BitField)<<"bytes"<<endl;
    }

    运行结果:

    Size of A : 16bytes
    Size of B : 12bytes
    Size of C : 10bytes
    Size of D : 8bytes
    Size of BitField : 8bytes
    A、B、C之所以不一样是因为字节对齐的问题。#pragma pack(push, 1)指令可以让编译器暂时调整对齐,设置为1字节。
    另外注意,char * 一般占4字节。

  • 相关阅读:
    linux brige中mac地址的比较
    BCM6358 加上TTL线 OPENWRT刷机全方位教程
    BCM6358 进入CFE界面
    BCM6358编译openwrt并刷机
    BCM6358开发板硬件资源 【OPENWRT刷机全方位教程】
    WRT54GS openwrt pppoe拨号
    CentOS6.5安装JDK1.8
    Sql Server 事物
    linux系统中的删除操作
    Java学习-集合的理解
  • 原文地址:https://www.cnblogs.com/jiji262/p/619567.html
Copyright © 2011-2022 走看看