Given
struct S {
SomeType single_element_in_the_struct;
};
Is it always true that
sizeof(struct S) == sizeof(SomeType)
Or it may be implementation dependent?
Given
struct S {
SomeType single_element_in_the_struct;
};
Is it always true that
sizeof(struct S) == sizeof(SomeType)
Or it may be implementation dependent?
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.
char[6]
will have a size of six bytes and a char[6][2]
will have a size of 12 bytes. I don't see the benefit of aligning a type struct S { char c[6]; };
differently than the element of type char[6]
that it contains. –
Pillar struct S = {char array[6]; char pad[2];}
Since the a 32-bit CPU is going to access 8 bytes anyhow, if struct S
is itself within a second array struct S aS[]
the elements of the array are then aligned on alignment boundaries. I wouldn't expect it to be common, but possible. I've seen people assume no such padding when directly writing structs via fwrite / write to a binary file or network socket, and it can and does break. –
Susuable 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.
© 2022 - 2024 — McMap. All rights reserved.
char array[6]
on a 32-bit system, may pad with 2 additional bytes to be a whole multiple of 4-bytes (32-bits). – Susuable