Struct alignment vs alignment of fields
via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Aug 9 02:00:10 PDT 2014
On Friday, 8 August 2014 at 18:20:41 UTC, ketmar wrote:
> yeah, chars (and bytes, and so on) are not aligned. i.e.
>
> align(1) struct B {
> int qtim;
> int bid;
> int ofr;
> int bidsiz;
> int ofrsiz;
> short mode;
> char ex;
> byte mmid;
> char z;
> }
>
> has sizeof == 25. not sure if specs mentions this, but they
> should.
It's not surprising that `char` and `byte` behave like this,
because `byte.alignof == 1`. But it's not obvious that this also
applies to arrays of them. I had expected them to be treated as
opaque objects of a certain size, and therefore have an alignment
that corresponds to their size.
pragma(msg, byte.alignof);
pragma(msg, (byte[1]).alignof);
pragma(msg, (byte[2]).alignof);
pragma(msg, (byte[3]).alignof);
pragma(msg, (byte[4]).alignof);
pragma(msg, (byte[5]).alignof);
pragma(msg, (byte[6]).alignof);
struct S {
byte a;
byte b;
byte c;
byte d;
}
struct T {
byte a;
short b;
int c;
}
pragma(msg, S.alignof);
pragma(msg, T.alignof);
This outputs "1" for all types except `T`, which has 4. So this
even applies to structs, not only arrays. Which may make sense,
because each element will always be accessed with correct
alignment. However, accessing the aggregate as a whole might
result in unaligned reads/writes.
More information about the Digitalmars-d-learn
mailing list