Search code examples
cmultidimensional-arraynested-loopsreversecs50

cs50 pset reflection filter


I'm trying to solve the reflection filter in the CS50 Week 4 pset, but I'm stuck. My logic is to use a buffer of type RGBTRIPLE to copy the last pixel from image[n][width - 1] to the first pixel image[n][n] throughout the entire image. However, there seems to be something wrong with my code:

void reflect(int height, int width, RGBTRIPLE image[height][width])
{
    for (int h = 0; h < height; h++)
    {
        RGBTRIPLE buffer;
        for (int w = 0; w < width; w++)
        {
            buffer = image[h][w];
            image[h][w] = image[h][width - w];
            image[h][width - w] = buffer;
        }
    }
    return;
}

Solution

  • Your code is incorrect at least because this expression image[h][width - w] can access memory beyond the image when h is equal to height - 1 and w is equal to 0, because the valid range of indices for a row of the array is [0, width).

    But even if you will use expression image[h][width - w - 1] the loop

    for (int w = 0; w < width; w++)
    

    will form the same original row as a result.

    If you want to reverse each row of the image then the function can look the following way

    void reflect( size_t height, size_t width, RGBTRIPLE image[height][width] )
    {
        for ( size_t h = 0; h < height; h++ )
        {
            for ( size_t w = 0; w < width / 2; w++ )
            {
                RGBTRIPLE buffer;
                buffer = image[h][w];
                image[h][w] = image[h][width - w - 1];
                image[h][width - w - 1] = buffer;
            }
        }
    }