The following struct X has 3 bytes of payload and 1 byte of padding:
struct X
{
short a;
char b;
};
memory layout: aab.
The following struct Y has 4 bytes of payload and 2 byte of padding:
struct Y
{
X x;
char c;
};
memory layout: aab.c.
Is there any way to keep X nested inside of Y and have sizeof(X) == 4 && sizeof(Y) == 4?
memory layout: aabc
Ideally, I would want this kind of space optimization for all types X (think X as a template parameter).
For hopefully obvious reasons the size of both
XandYcan’t be four (if it were possible,Xwould have multiple definitions, the normal padded one and one where the padding is used by thecharofY). So the only wayYcould be 4 is ifXwere changed to eliminate its padding. This can be done by compiler specific pragmas or directives. However, since that could result inXbeing accessed unaligned it would effectively restrict possible portability of your program (some architectures will even crash if misaligned accesses are made).Instead, can you explain more clearly the end result you’re hoping to achieve here?