Size of struct with a single element
Given
struct S {
SomeType single_element_in_the_struct;
};
Is it always true that
sizeof(struct S) == sizeof(SomeType)
Or it may be implementation dependen开发者_Go百科t?
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.
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.
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.
精彩评论