CS50 Week4 Reflect函数问题:首列全为0与check50报错排查
图像反射函数首行像素错误排查与修复
- 运行check50时触发错误,本地测试图像反射功能时,每一行的首列像素始终为(0,0,0),而非预期的原始图像对应位置像素。以3x3测试图像为例,预期首行全为(255,0,0),实际首行首列是(0,0,0),怀疑循环逻辑存在问题。
测试详情
错误原因
expected "255 0 0\n255 0...", not "0 0 0\n255 0 0..."
测试日志
testing with sample 3x3 image
first row: (255, 0, 0), (255, 0, 0), (255, 0, 0)
second row: (0, 255, 0), (0, 255, 0), (0, 0, 255)
third row: (0, 0, 255), (0, 0, 255), (0, 0, 255)
running ./testing 2 2...
checking for output "255 0 0\n255 0 0\n255 0 0\n0 255 0\n0 255 0\n0 255 0\n0 0 255\n0 0 255\n0 0 255\n"...
预期输出
255 0 0 255 0 0 255 0 0 0 255 0 0 255 0 0 255 0 0 0 255 0 0 255 0 0 255
实际输出
0 0 0 255 0 0 255 0 0 0 0 0 0 255 0 0 255 0 0 0 0 0 0 255 0 0 255
问题代码
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 = 1 ; w < width ; w++) { reflected[h][w] = image[h][width-1 - 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; }
问题分析与修复
问题出在内层循环的起始索引:
- 原代码中内层循环
w从1开始,导致w=0的位置(每一行的首列)从未被赋值,reflected数组中这些位置保留默认的(0,0,0),最终覆盖到原图像后就出现首列全黑的错误。 - 正确的循环应该从
w=0开始,遍历每一列的所有索引。
修复后的代码:
void reflect(int height, int width, RGBTRIPLE image[height][width]) { // 存储反射后的图像 RGBTRIPLE reflected[height][width]; for (int h = 0 ; h < height ; h++) { // 从w=0开始遍历每一列 for (int w = 0 ; w < width ; w++) { reflected[h][w] = image[h][width-1 - w]; } } // 将反射结果复制回原图像 for (int h = 0 ; h < height ; h++) { for (int w = 0 ; w < width ; w++) { image[h][w] = reflected[h][w]; } } return; }
另外可以优化实现——不需要额外数组,直接在原图像上交换左右对称像素,节省内存:
void reflect(int height, int width, RGBTRIPLE image[height][width]) { for (int h = 0; h < height; h++) { // 只遍历前半列,和后半列对称交换 for (int w = 0; w < width / 2; w++) { RGBTRIPLE temp = image[h][w]; image[h][w] = image[h][width - 1 - w]; image[h][width - 1 - w] = temp; } } return; }
内容的提问来源于stack exchange,提问作者Ahmed Hesham
相关产品推荐
相关产品推荐

