cs50 反映代码失败。价值观不在正确的地方

问题描述 投票:0回答:1

尽管我自己测试时图片反映正确,但我找不到解决这两个错误的方法。 这是错误

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;
}

尝试以不同的方式编写代码,但我最终遇到了同样的错误。

c cs50 swap
1个回答
0
投票

您必须始终检查您的范围:

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]
修复它。

© www.soinside.com 2019 - 2024. All rights reserved.