Ian said:
The compiler is free to insert padding to ensure correct alignment of
the struct members.
No. it's padding.
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_data) == ";
cout << sizeof(test_data) << endl << endl;
cout << "Using default alignment:" << endl;
cout << "sizeof(test_data2) == ";
cout << sizeof(test_data2) << endl;
return 0;
}
On my computer, the output looks like this:
Using 1-byte alignment:
sizeof(test_data) == 5
Using default alignment:
sizeof(test_data2) == 8
You can see that with the #pragma in place, sizeof(test_data) is 5, as
you may expect from examining the contents of test_data.
In contrast, sizeof(test_data2) 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.