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
来检查您是否找到了颜色,您可以在其中设置x
和y
坐标
假设每行末尾没有额外的填充,并且每个像素都是 8 位,则内部 for 循环的内容将是:
if (*(array + z * cols + c) == color)
{
*x = c;
*y = z;
return 1;
}
关于c - 在c中定位数组中的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26725861/