You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

图像滤镜程序像素交换函数报错:indirection require pointer operand

解决滤镜程序中“indirection requires pointer operand”指针错误

问题描述

开发滤镜程序时,实现像素交换的reflect函数出现指针错误,报错提示“indirection requires pointer operand”。思路是用临时变量存储首个像素的RGB值,将最后一个像素值赋给首个像素,再把临时变量的值赋给最后一个像素,但对指针的理解可能存在误区。

错误代码

void reflect(int height, int width, RGBTRIPLE image[height][width])
{
      for (int i = 0; i <= height; i++)
    {
        for (int j = 0; j <= width / 2; j++)
        {

            // assign corresponding values to temporary storage
            int tempGreen = *image[i][j].rgbtGreen;
            int tempRed = *image[i][j].rgbtRed;
            int tempBlue = *image[i][j].rgbtBlue;

            // assign last pixel value to first pixel
            *image[i][j].rgbtGreen = *image[i][width-j].rgbtGreen;
            *image[i][j].rgbtRed = *image[i][width-j].rgbtRed;
            *image[i][j].rgbtBlue = *image[i][width-j].rgbtBlue;

            // assign first pixel value to las pixel
            *image[i][j].rgbtGreen = tempGreen;
            *image[i][j].rgbtRed = tempRed;
            *image[i][j].rgbtBlue = tempBlue;

        }
    }
    return;
}

终端报错信息

helpers.c:55:29: error: indirection requires pointer operand ('int' invalid)
            int tempGreen = *image[i][j].rgbtGreen;
                            ^~~~~~~~~~~~~~~~~~~~~~
fatal error: too many errors emitted, stopping now [-ferror-limit=]
2 errors generated.
make: *** [<builtin>: helpers] Error 1

问题分析与修复方案

1. 核心错误:不必要的指针解引用

RGBTRIPLE结构体中的rgbtGreen、rgbtRed、rgbtBlue是普通数值类型(通常是BYTE,即无符号字符),不是指针。你错误地对这些非指针值使用了*解引用操作符,这就是报错的直接原因。

2. 循环边界错误

  • 外层循环i <= height会导致数组越界,因为数组索引从0开始,有效行索引范围是0到height-1,应改为i < height。
  • 内层循环j <= width / 2会让中间位置的像素被重复交换(当宽度为奇数时),应改为j < width / 2。
  • 右侧像素的索引错误:width-j会超出数组范围(比如width=5时,j=0对应5,超出最大索引4),正确的右侧索引应为width - 1 - j。

3. 交换逻辑错误

最后一步你把临时变量的值又赋回给了原左侧像素,等于没有完成交换,应该把临时值赋给对应的右侧像素。

修复后的代码

void reflect(int height, int width, RGBTRIPLE image[height][width])
{
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width / 2; j++)
        {
            // 存储左侧像素的RGB值
            int tempGreen = image[i][j].rgbtGreen;
            int tempRed = image[i][j].rgbtRed;
            int tempBlue = image[i][j].rgbtBlue;

            // 右侧像素值覆盖左侧像素
            image[i][j].rgbtGreen = image[i][width - 1 - j].rgbtGreen;
            image[i][j].rgbtRed = image[i][width - 1 - j].rgbtRed;
            image[i][j].rgbtBlue = image[i][width - 1 - j].rgbtBlue;

            // 临时值覆盖右侧像素,完成交换
            image[i][width - 1 - j].rgbtGreen = tempGreen;
            image[i][width - 1 - j].rgbtRed = tempRed;
            image[i][width - 1 - j].rgbtBlue = tempBlue;
        }
    }
    return;
}

内容的提问来源于stack exchange,提问作者CarriedNeko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 19:55:12