0

Ive just got to pset4 and it seems a bit of a jump from pset3, I'm trying to understand how everything works before diving into the problem.

This loop in my mind which is copying the bmp files goes over every pixel and copies it to the new file. To me it seems that in the fread and fwrite functions 3 arguments &triple, 1, inptr/outptr are constant.However i just don't see how the sizeof(RGBTRIPLE) is changing value in this loop, as 'i' and 'j' don't seem to interact with it.

for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++)
{
    // iterate over pixels in scanline
    for (int j = 0; j < bi.biWidth; j++)
    {
        // temporary storage
        RGBTRIPLE triple;

        // read RGB triple from infile
        fread(&triple, sizeof(RGBTRIPLE), 1, inptr);

        // write RGB triple to outfile
        fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr);
    }

    // skip over padding, if any
    fseek(inptr, padding, SEEK_CUR);

    // then add it back (to demonstrate how)
    for (int k = 0; k < padding; k++)
    {
        fputc(0x00, outptr);
    }
}
1

It doesn't change, nor should it.

fread(&triple, sizeof(RGBTRIPLE), 1, inptr); says ... read from the file called inptr, 3 bytes (the size of a pixel) and store it in the variable called triple.

Because that is inside of a for loop, it will happen bi.biWidth times.

So if you imagine the bitmap small.bmp, which looks like this (I've added the spaces for clarity):

00ff00 00ff00 00ff00 00 00 00
00ff00 ffffff 00ff00 00 00 00
00ff00 00ff00 00ff00 00 00 00

the first fread will read in 3 bytes 00ff00 and write them out, and because the width is 3, that loop will repeat 3 times, so your output file now has

00ff00 00ff00 00ff00

then the padding loop will run and write the 3 bytes of padding and you'll have

00ff00 00ff00 00ff00 00 00 00

and then the overall loop (for the height) makes it run another two times, until you have the complete copy.

fyi. answered your same question at /r/cs50

| improve this answer | |

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .