尽管我自己测试时图片反映正确,但我找不到解决这两个错误的方法。 这是错误
testing with sample 1x3 image
first row: (255, 0, 0), (0, 255, 0), (0, 0, 255)
running ./testing 2 1...
checking for output "0 0 255\n0 255 0\n255 0 0\n"...
0 0 255
0 255 0
255 0 0
0 0 0
0 0 255
0 255 0
我注意到第一行有一个第二行的值,第二行有一个第三行的值。 这是代码:
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
//this is where the reflected image gonna be
RGBTRIPLE reflected[height][width];
for (int h = 0 ; h < height ; h++)
{
for (int w = 0 ; w < width ; w++)
{
reflected[h][w] = image[h][width - w];
}
}
//copying from the reflected to the image
for (int h = 0 ; h < height ; h++)
{
for (int w = 0 ; w < width ; w++)
{
image[h][w] = reflected[h][w];
}
}
return;
}
尝试以不同的方式编写代码,但我最终遇到了同样的错误。
您必须始终检查您的范围:
image[r][c]
假设0 <= r < height
和0 <= c < width
.
现在考虑你的
image[h][width-w]
。 width-w
的范围是多少?当w = 0 => width-w = width
。超出范围(和 UB)。
你只需用
image[h][width-1 - w]
修复它。