Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C struct elements alignment (ansi)

just a simple question... what the standard says about the structure members alignment? for example with this one:

struct
{
    uint8_t a;
    uint8_t b;
    /* other members */
} test;

It is guarateed that b is at offset 1 from the struct start? Thanks

like image 239
Davide Avatar asked Jan 11 '23 15:01

Davide


2 Answers

The standard (as of C99) doesn't really say anything.

The only real guarantees are that (void *)&test == (void *)&a, and that a is at a lower address than b. Everything else is up to the implementation.

like image 147
Oliver Charlesworth Avatar answered Jan 21 '23 17:01

Oliver Charlesworth


C11 6.7.2.1 Structure and union specifiers p14 says

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

meaning that you can't make any portable assumptions about the difference between the addresses of a and b.

like image 22
simonc Avatar answered Jan 21 '23 17:01

simonc