0
#include "helpers.h"

void colorize(int height, int width, RGBTRIPLE image[height][width])
{
    // Change all black pixels to a color of your choosing
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            RGBTRIPLE pixel = image[i][j];
            if (pixel.rgbtRed == 0x00 && pixel.rgbtBlue == 0x00 && pixel.rgbtGreen == 0x00)
            {
                pixel.rgbtRed = 0xFF;
            }
        }
    }
}

We're trying to change the black pixels of a smiley face to a different color. I choose Red. Black is when all the RGB is 0, so I check for that. If that's correct, I make Red equal to FF. But when it compiles, it's like nothing happened. Here's the definition of RGB triple.

typedef struct
{
    BYTE  rgbtBlue;
    BYTE  rgbtGreen;
    BYTE  rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE;

1 Answer 1

0

The problem is you are not changing the value in image.

When you say RGBTRIPLE pixel = image[i][j] the value of that RGBTRIPLE in the image array at that location is copied into a variable called pixel

Then when you perform the assignment below, the change isn't persisted anywhere because the change wasn't done to image[i][j]. It only altered a temporary variable that has no effect since it is just recreated in each loop pass. ( in fact your compiler will probably optimize out the entire function since it has no effect )

Here's one way to fix your code:

void colorize(int height, int width, RGBTRIPLE image[height][width])
{
    // Change all black pixels to a color of your choosing
    RGBTRIPLE *pixel = 0;
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            pixel = &image[i][j]; //assign pixel point to the target
            if (pixel->rgbtRed == 0x00 && 
                pixel->rgbtBlue == 0x00 &&
                pixel->rgbtGreen == 0x00)
            {
                pixel->rgbtRed = 0xFF; //actually modifies the image array
            }
        }
    }
}

Now I am making pixel a pointer to the 'pixel' in image that you want to test and augment so the change is ACTUALLY made to the image array.

An alternative to this would be to use image[i][j] directly instead of pixel in all those locations in which case you'd use the . operator instead of -> as that's only used for pointers.

You must log in to answer this question.

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