Size of struct with a single element

前端 未结 3 1082
半阙折子戏
半阙折子戏 2020-12-11 14:58

Given

struct S {
  SomeType single_element_in_the_struct;
};

Is it always true that

sizeof(struct S) == sizeof(SomeType)


        
相关标签:
3条回答
  • 2020-12-11 15:25

    It does not have to be equal, due to structure padding.

    section 6.7.2.1 in the C99 standard states that "There may be unnamed padding within a structure object, but not at its beginning".

    This is refered to as structure padding. Paddings may be added to make sure that the structure is properly aligned in memory. The exakt size of a structure can change if you change the order of its members.

    0 讨论(0)
  • 2020-12-11 15:28

    This will usually be the case, but it's not guaranteed.

    Any struct may have unnamed padding bytes at the end of the struct, but these are usually used for alignment purposes, which isn't a concern if you only have a single element.

    0 讨论(0)
  • 2020-12-11 15:41

    It depends on the packing of your compiler. Usually the size of a structure is divisible by the word-length of your system (e.g. 4 byte == 32 bit).

    So you will often have sizeof(struct S) > sizeof(SomeType)

    For most compilers you can modify the packing size using compiler pragmas. If you set #pragma pack(1) then the sizes should be equal.

    0 讨论(0)
提交回复
热议问题