c - 在c中定位数组中的颜色

标签 c colors coordinates locate

int locate_color(  const uint8_t array[], 
           unsigned int cols, 
           unsigned int rows,
           uint8_t color,
           unsigned int *x,
           unsigned int *y )
{
    for (int z = 0; z < rows; z++)
    {
        for (int c = 0; c < cols; c++)
        { 
            if (array[z] == color)
            {
                *x = color;
            }
            if (array[c] == color)
            {
                *y = color;
            }
            return 1;
    }
    return 0;
}

该函数是从数组中定位颜色的函数。它从左到右、从上到下搜索,找到后,将坐标存储到 *x 和 *y 中。但是当我运行代码时,它给了我一个错误。谁能告诉我哪里出错了?

最佳答案

您有几个问题:

  • 您需要以不同的方式访问数组元素,例如:

    if (*(array + z * cols + c) == color)
    

    这将使指针array衰减到z(行索引)乘以行的长度,加上c(列索引),然后取消引用它以获取其中的元素以与 color 进行比较。

  • 您需要将*x*y设置为行(z)和列(c)您在其中找到了颜色,而不是颜色本身。

  • 内部 for 循环末尾缺少大括号 (})

  • 您只需要一个if来检查您是否找到了颜色,您可以在其中设置xy坐标

假设每行末尾没有额外的填充,并且每个像素都是 8 位,则内部 for 循环的内容将是:

        if (*(array + z * cols + c) == color)
        {
            *x = c;
            *y = z;
            return 1;
        }

关于c - 在c中定位数组中的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26725861/

相关文章:

c - 如何连接两个包含多个空字符的字符串?

macos - 在Mac OS X中修改窗口按钮的颜色

image - 将 RGBA 颜色转换为 RGB

.net - 将坐标变换到另一个坐标系

javascript - 根据管端法线将旋转应用于圆柱体

c - 如何编写编译器 "understandable"C 代码?

c - 在管道之后恢复标准输入

c - 通过管道将结构传递给 C 中的 child

configuration - PhpStorm-更改更改的行的大小和颜色

3d - 将3D位置转换为2d屏幕位置[r69!]