简体   繁体   中英

Structure padding and alignment of byte-sized fields?

If I have a structure such as the one below, on a 32-bit machine, will there be any padding within the structure? As I understand it, the structure will align everything to it's largest field, so what if the largest field is a byte (uint8)?

struct s {
    uint8_t a[32];
    uint8_t b[64];
};

Thanks.

There may be padding between the members.

C standard 6.7.2.1(15): Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

(14) Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.

There is probably no padding between the members on a modern machine, but C doesn't guarantee it, so don't rely on it.

You can determine if there is padding using the ofsetoff() macro and then manage that with static assert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM