Reputation: 1577
I have a struct
that looks something like the following:
typedef unsigned __int16 UINT16;
typedef unsigned __int64 UINT64;
struct Example {
struct {
UINT64 var1 : 5;
UINT64 var2 : 2;
UINT64 var3 : 29;
UINT64 var4 : 23;
UINT64 : 5;
};
struct {
UINT16 var5 : 4;
UINT16 var6 : 2;
UINT16 : 10;
};
};
I was expecting sizeof(struct Example)
to return 10
, but it returned 16
. I have no clue why this is happening, and I would appreciate any input on the matter.
Upvotes: 1
Views: 179
Reputation: 225507
This is due to alignment of the fields.
The first internal struct uses a uint64_t
as the underlying type for the bitfield, while the second uses a uint16_t
as the underlying type.
In order for the struct as a whole to be properly aligned, it must be aligned at the same offset as that required by the largest "base" internal field, which in this case is a uint64_t
and therefore requires 8 byte alignment.
Without such alignment, if an array of this type is created then not all array elements will start on an 8 byte offset. So 6 padding bytes are added at the end to ensure proper alignment.
Upvotes: 6