2

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.

Quantifeye
  • 261
  • 2
  • 10
  • 2
    Look up `#pragma pack` and maybe related questions if that alone doesn't fix the problem. – nwp May 17 '17 at 11:43

4 Answers4

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

Community
  • 1
  • 1
TheWaterProgrammer
  • 7,055
  • 12
  • 70
  • 159
  • 1
    the thing is that `char a4` fits exactly to the last padding byte, but compilers aren't allowed to pack it into that place. It looks like the OP wants that behavior without packing. See [Standard-layout and tail padding](https://stackoverflow.com/q/53837373/995714) – phuclv Dec 01 '20 at 08:14
0
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;
}
Dilip Kumar
  • 33
  • 1
  • 5
0

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.

-1

using

#pragma pack(1)

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

PeXXeR
  • 101
  • 1
  • 2
  • 10