Can C arrays contain padding in between elements?

后端 未结 5 737
长情又很酷
长情又很酷 2020-11-27 19:55

I heard a rumor that, in C, arrays that are contained inside structs may have padding added in between elements of the array. Now obviously, the amount of padding could not

5条回答
  •  [愿得一人]
    2020-11-27 20:47

    Yes, sort of. Variables are often aligned to some boundry, depending on the variable. Take the following, for instance:

    typedef struct
    {
        double d;
        char c;
    } a_type_t;
    

    double and char are 8 and 1 bytes, on my system, respectively. Total of 9. That structure, however, will be 16 bytes, so that the doubles will always be 8-byte aligned. If I had just used ints, chars, etc, then the alignment might be 1, 2, 4, or 8.

    For some type T, sizeof(T) may or may not equal sizeof(T.a) + sizeof(T.b) + sizeof(T.c) ... etc.

    Generally, this is entirely compiler and architecture dependent. In practice, it never matters.

提交回复
热议问题