struct Foo {
int a;
char b;
};
Will it be guaranteed in this case that b
will have an offset of sizeof(int)
in the struct? Will it be guaranteed that members will be packed together as long as all alignment requirements are being met, no padding required (Not taking into account the padding at the end to align the structures size to the largest member)?
I ask this because I would like to know if simply using fwrite()
or write()
to save a struct
to a file can cause problems if the layout of a struct
is not consistent across platforms, because then each save file would be specific to the platform on which it was created.
There are no guarantees. If a compiler wishes to insert unnecessary padding between structure members, it can do so. (For example, it might have determined that a particular member could be handled much more efficiently were it eight-byte aligned, even though it doesn't require alignment at all.)
Portable code intended for interoperability should not fwrite
struct
s. Aside from the potential of differences in padding, not all platforms use the same endianness, nor the same floating point representation (if that's relevant).