Alignment of elements of structure C (ansi)

just a question ... what does the standard say about aligning structural elements? for example with this:

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

It turns out that b is at offset 1 from the beginning of the structure? Thanks

+4
source share
6 answers

The standard (with C99) actually says nothing.

The only real guarantees are (void *)&test == (void *)&aand that ahas a lower address than b. Everything else is implementation dependent.

+7
source

C11 6.7.2.1. P14 structure and join specifiers say

, .

, - a b.

+1

offsetof, .

C - , , C99 6.7.2.1 12 ( C11 14), :

, .

13 :

, - , , . , , ( -, , ) . , .

++ 9.2 , 13, :

(non-union) ( 11) , . ( 11). , ;

19 :

, reinterpret_cast, ( , , ) . [ : , , , . -end note]

+1

, , , uint_8 , , uint_8 uint_16.

- :

{
    uint8_t a;
    uint8_t b;

    uint_32 c; // where is C, at &a+2 or &a+4 ?
    /* other members */
} test;

...

0

K & R (ANSI C) 6.4 (. 138) :

, , . - "".

, ANSI C , b 1.

, b offset sizeof(int) , , .

pack-pragmas, , struct "" , .

0
source

What is guaranteed by C-Standard has already been mentioned in other answers.

However, in order for it to b be at offset 1, your compiler could offer options to "pack" the structure, it will say that it explicitly adds no addition .

For gcc, this can be achieved with . #pragma pack()

#pragma pack(1)
struct
{
  uint8_t a; /* Guaranteed to be at offset 0. */
  uint8_t b; /* Guaranteed to be at offset 1. */
  /* other members are guaranteed to start at offset 2. */
} test_packed;
#pragma pack()

struct
{
  uint8_t a; /* Guaranteed to by at offset 0. */
  uint8_t b; /* NOT guaranteed to be at offset 1. */
  /* other members are NOT guaranteed to start at offset 2. */
} test_unpacked;

A portable (and saved) solution would be to simply use an array:

struct
{
  uint8_t ab[2]; /* ab[0] is guaranteed to be at offset 0. */
                 /* ab[1] is guaranteed to be at offset 1. */
  /* other members are NOT guaranteed to start at offset 2. */
} test_packed;
0
source

All Articles