Packing of Struct Fields

Adam D. Ruppe destructionator at gmail.com
Sat Oct 17 13:23:38 UTC 2020


On Saturday, 17 October 2020 at 13:00:59 UTC, Per Nordlöw wrote:
> I understand that. I don't want the alignment of `S` to change. 
> I want the padding after `s`

That padding is part of S. It is at the end, after its fields, 
but still part of it.

S's layout doesn't depend on what else is around it.

> in `T` to be avoided and have `c` start at byte-offset 7.

Use a union.

     struct S
     {
         int i;                  // 4 bytes
         short s;                // 2 byte
         bool b;                 // 1 byte
     }
     static assert(S.sizeof == 8);
     static assert(S.alignof == 4);

struct T {
    union {
        S s;
        struct {
            align(1):
            ubyte[7] _ignore_me;
            char c;
        }
    }
}

static assert(T.alignof == 4);
static assert(T.sizeof == 8);
static assert(T.c.offsetof == 7);



More information about the Digitalmars-d-learn mailing list