Packing nested structs in C++

北战南征 提交于 2021-01-01 07:30:41

问题


Using Visual Studio 2017, the following gives...

struct AAA // 15 bytes
{
    double d;
    short s;
    char a1;
    char a2;
    char a3;
    char s4;
    char s5;
};

struct BBB
{
    AAA d;
    char a4;
};

int main()
{
    std::cout << sizeof(AAA) << "\n"; // gives 16
    std::cout << sizeof(BBB) << "\n"; // gives 24
    getchar();
    return 0;
}

The Question is... how do I get sizeof(BBB) to be 16.


回答1:


Use #pragma pack(push, 1) or #pragma pack(1) to enforce compiler not to line up structure members on 2 byte or 4 byte boundaries which makes it easier and faster for the processor to handle. So the structure contains secret padding bytes to make this happen. But this increases memory usage because of padding.

Its a precise explanation here




回答2:


struct AAA // 15 bytes
{
    double d;
    short s;
    char a1;
    char a2;
    char a3;
    char s4;
    char s5;
};

#pragma pack(1)

struct BBB
{
    AAA d;
    char a4;
};

int main()
{
    std::cout << sizeof(AAA) << "\n"; // gives 16
    std::cout << sizeof(BBB) << "\n"; // gives 17
    getchar();
    return 0;
}



回答3:


Try with below code :

#pragma pack(1)
struct AAA // 15 bytes
{
    double d;
    short s;
    char a1;
    char a2;
    char a3;
    char s4;
    char s5;
};

#pragma pack(1)
struct BBB
{
    AAA d;
    char a4;
};

int main(int argc, char *argv[])
{        
    std::cout << sizeof(AAA) << "\n"; // gives 15
    std::cout << sizeof(BBB) << "\n"; // gives 16
    getchar();


    return 0;
}

The result will be :

15
16

structs, and unions have stricter alignment requirements that ensure consistent aggregate and union storage and data retrieval. There is suggested alignment for the scalar members of unions and structures. Structure size must be an integral multiple of its alignment, which may require padding after the last member.

#pragma pack statement change the alignment of a structure.




回答4:


using

#pragma pack(1)

will results into sizeof(AAA) to be 15 and sizeof(BBB) to be 16.



来源:https://stackoverflow.com/questions/44023837/packing-nested-structs-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!