// assume file points to a file
struct myStruct
{
WORD word;
WORD word2;
};
Two competing codes: (1)
myStruct a;
a.word = 0xABCD;
a.word2 = 0xFADB;
fwrite(&a, sizeof(myStruct), 1, file);
output:
cdab dbfa
versus: (2)
DWORD word = 0xABCDFADB;
fwrite(&word, sizeof(DWORD), 1, file);
output:
dbfa cdab
My question is this: why isn’t fwrite amenable to writing the structure? I would assume that (1) would have equivalent output to (2). However, the fwrite is reading each struct member variable individually (and then writing them in little-endian order). Instead, I was expecting (1) to read the whole struct as one contiguous chunk, and start writing binary data starting at the end of this chunk (instead of at the end of the first member variable).
Thoughts?
If you’re on a little-endian architecture, whole structs aren’t stored backwards; only the integers, pointers, and other numeric values are.
Thus, when you have a struct containing two
WORDs, eachWORDis stored in little-endian order, but the fields themselves aren’t switched in memory. When you have a singleDWORD, that’s a single unit, and it will be stored in little-endian.