I'm trying to write a program in C that scales bitmap images by a given factor, when I use fwrite()
inside a loop to do so:
// Go through each pixel of input bitmap
for (int y = 0; y < inWidth; y++)
{
fread(pixel, sizeof(RGBTRIPLE), 1, inBMP);
// Write each pixel to output bitmap (factor) times
for (int z = 0; z < factor; z++)
{
fwrite(pixel, sizeof(RGBTRIPLE), 1, outBMP);
}
}
Everything works:
But when I use fwrite()
without a loop:
// Go through each pixel of input bitmap
for (int y = 0; y < inWidth; y++)
{
fread(pixel, sizeof(RGBTRIPLE), 1, inBMP);
// Write each pixel to output bitmap (factor) times
fwrite(pixel, sizeof(RGBTRIPLE), factor, outBMP);
}
I get this:
Why does that happen ?
The problem is the third parameter, count
, indicates how many elements are in the array pointed to by ptr
, not how many times the instance pointed to as ptr
should be written. You're basically writing garbage that's in memory behind what's ptr
is pointing to.
See the docs for more details.