0
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;
}

This function is a function that locates a color from an array. It searches from left to right and top to bottom, and when it is found, it stores the coordinates into the *x and *y. But when I ran the code, it gave me an error. Would anyone be able to tell me where I went wrong?

user3880587
  • 69
  • 2
  • 12
  • The title of your question doesn't describe the problem. You should better set it, for example to: *got an `error ` in a loop*, or something like that. – yulian Nov 04 '14 at 00:50

2 Answers2

1

You have several issues:

  • You need to access the array elements differently, something like:

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

    That will offset the pointer array decays to by z (the row index) times the length of a row, plus c (the column index), then dereference it to get the element there to compare against color.

  • You need to set *x and *y to the row (z) and column (c) you found the color in, not to the color itself.

  • You're missing a brace (}) at the end of your inner for loop

  • You only need one if to check that you've found the color, within which you can set both the x and y coordinates

Assuming no extra padding at the end of each row, and that each pixel is 8 bits, the contents of your inner for loop would be:

        if (*(array + z * cols + c) == color)
        {
            *x = c;
            *y = z;
            return 1;
        }
Dmitri
  • 9,175
  • 2
  • 27
  • 34
0

const uint8_t array is a one dimension array. I believe you expect a two dimension array which is like:

array[z][c];

for (int z = 0; z < rows; z++)
{
    for (int c = 0; c < cols; c++)
    { 
        if (array[z][c] == color)
        {
            *x = color;
            *y = color;
            return 1;   // return 1 only if you find the matching color.
        }  
    }
}
Kaizhe Huang
  • 990
  • 5
  • 11