struct is wrong size

I'm trying to write stuff to a bmp-file, and I'm having trouble with the file-header. My struct looks like this:

1
2
3
4
5
6
7
typedef struct {
	unsigned short bfType;		//"BM"
	unsigned int bfSize;		//filesize
	unsigned short res1; 	//zero
	unsigned short res2; 	//zero
	unsigned int offset;		//offset to beginning of map
} FILEHEADER;


Now, if I can count properly, this should be 14 bytes in size, which is correct according to the bmp spec. However, sizeof(FILEHEADER) returns 16, not 14. Anybody know what I'm doing wrong?
Looks like 14 to me too.

3*short(2) = 6
2*int(4) = 8

8+6 = 14

Maybe you need to rebuild the project? Are you sure you're using the latest build?

Or maybe you're somehow adding two to the result of sizeof(FILEHEADER)?

Try removing one of the shorts and seeing what the sizeof reads.
This is the usual thing about structure padding ( there's lots of info about this on the internet).

I know that GCC and MSVC certainly have compiler directives that will do away with the padding and make the struct an exact fit (so to speak).


On GCC - there is the __attribute__ ((__packed__)) compiler directive -
but a quick recheck on the web shows that there have been recent problems with this directive (it may be broken).

On MSVC compilers there is the pragma packed directive.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#pragma pack(push,1)

struct  MyStructA
{
	unsigned short bfType;		//"BM"
	unsigned int bfSize;		//filesize
	unsigned short res1; 	//zero
	unsigned short res2; 	//zero
	unsigned int offset;    
} ;
#pragma pack(pop)

struct  MyStructB
{
	unsigned short bfType;		//"BM"
	unsigned int bfSize;		//filesize
	unsigned short res1; 	//zero
	unsigned short res2; 	//zero
	unsigned int offset;    
};



int main () 
{
    	 	
	 
    cout << sizeof(MyStructA) << "   " << sizeof(MyStructB) << endl;
}
14   16


There are other work arounds
EDIT - the workaround I'm talking about being of course being the
tried and tested method of having header packing/unpacking functions.
Last edited on
Topic archived. No new replies allowed.