Ian Collins wrote:
Chameleon wrote:
I have a TGA image header struct.
TGA has 18 bytes header, so the C struct too.
why this return 20?
sizeof(TGAHeade r)
The compiler is free to insert padding to ensure correct alignment of
the struct members.
I saw this in many structs. I believe compiler round up the size to 4
multiple.
No. it's padding.
Compiler is mingw gcc. Why this happens?
how can I pass the size in fread without hardcode the header size?
You simply can't. Unless your platform has a means of packing
structures. Even it if does, the cost due to misaligned access may be
to high to justify their use.
Properly packed structures can be crucial when reading data from binary
file headers, as the OP appears to be doing with the TGAHeader
structure.
Your compiler may have a "#pragma option" feature that you can use to
wrap your structure definition, to enforce the byte alignment you want.
You have to refer to your documentation for details.
For example, in Borland C++ Builder 6, I would use:
#include <iostream>
#pragma option push -a1 // set 1 byte alignment
struct test_data
{
char c;
int value;
};
#pragma option pop // restore original byte alignment
// Exactly the same structure, but using default alignment
struct test_data2
{
char c;
int value;
};
int main(int argc, char* argv[])
{
using namespace std;
cout << "Using 1-byte alignment:" << endl;
cout << "sizeof(test_da ta) == ";
cout << sizeof(test_dat a) << endl << endl;
cout << "Using default alignment:" << endl;
cout << "sizeof(test_da ta2) == ";
cout << sizeof(test_dat a2) << endl;
return 0;
}
On my computer, the output looks like this:
Using 1-byte alignment:
sizeof(test_dat a) == 5
Using default alignment:
sizeof(test_dat a2) == 8
You can see that with the #pragma in place, sizeof(test_dat a) is 5, as
you may expect from examining the contents of test_data.
In contrast, sizeof(test_dat a2) is 8, even though the structures have
identical contents. This is because the compiler pads the fields to
make them line up on 4-byte boundaries in this case.
Your results may be different, depending on which platform you are
using.
Regards,
Markus.