I can see a lot of problems with your code:
1. Inconsistent sizes of data types
On different platforms, types like int
and short
can have different sizes. So, int
might be one size on one platform, and another size on a different platform. You may need to use exact sized types like uint32_t
.
2. Padding and alignment
The headers stored in the files are packed. Your structs are aligned. That means that the compiler inserts padding between members to ensure that members are always aligned for optimal memory access.
There are a variety of ways of dealing with this. You could declare your structs to be packed. That would get you so far, but see the next point.
3. Endianness
If you are reading a Windows bitmap on a big endian system, you have convert from little endian data in the file to big endian data for your system.
4. xResolution, yResolution are the wrong members
These are meant to indicate a physical size of the pixels. In practice they are seldom specified. You meant to read Width
and Height
.
5. The VLA (gah!)
You are using a variable length array: struct PIXEL arr[InfoHeader.xResolution][InfoHeader.yResolution]
. That is liable to lead to stack overflows for large bitmaps. You really need to use dynamically allocated memory for the pixel array.
How would I deal with these issues?
- Use exact sized types.
- Declare packed structs.
- Read the structs from file, and then perform endian correction if needed.
- Allocate the pixel array with
malloc
.