使用“temp”数组在 C 中水平反射(翻转)图像

Jas*_*ter 1 c

我试图反射(水平翻转)图像,但我似乎不太明白为什么图像不反射并保持原始状态。我尝试了许多不同的方法(添加-1[width - j]分配tempArrayasRGBTRIPLE tempArray;width除以/2as 循环条件。

没有抛出任何错误,我已经遵循了 Stackoverflow 的解决方案,但似乎我还没有完全达到目标,有什么建议吗?

// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
    RGBTRIPLE tempArray[height][width];

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            tempArray[i][j] = image[i][j];
            image[i][j] = image[i][width - j];
            image[i][width - j] = tempArray[i][j];
        }
    }
    return;
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*opp 5

正如评论中提到的,您有两个问题。首先,由于您迭代整行,因此最终将每个项目交换 2 次。这样就只剩下原始数组了。

image[i][width - j]其次,您可以使用when访问数组末尾后面的一个j == 0。数组的有效索引是0...(length-1).

另一个小问题是您不需要临时值的数组。

// Reflect image horizontally
void reflect(int height, int width, int image[height][width])
{
    int temp;

    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width / 2; j++)
        {
            temp = image[i][j];
            image[i][j] = image[i][width - j - 1];
            image[i][width - j - 1] = temp;
        }
    }
    return;
}
Run Code Online (Sandbox Code Playgroud)

测试: https: //ideone.com/EAALtI