Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check the contents of an array?

Tags:

arrays

c

I want to check if a char array contains all '0's.

I tried this, but it doesn't work:

char array[8];
// ...
if (array == {'0','0','0','0','0','0','0','0'})
   // do something

How do I do this?

like image 731
trunks1ace Avatar asked May 27 '15 12:05

trunks1ace


People also ask

What are the contents of an array?

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.


3 Answers

This

array == {'0','0','0','0','0','0','0','0'}

is definitely wrong, and surely not compiling.

You can compare the values with memcmp() like this

int allZeroes = (memcmp(array, "00000000", 8) == 0);
like image 70
Iharob Al Asimi Avatar answered Nov 09 '22 04:11

Iharob Al Asimi


In fact

array == {'0','0','0','0','0','0','0','0'}

is not allowed, you cannot compare arrays like this. Rather, do it in a loop:

int row_is_all_zeroes(char arr[8])
{
  for (int i = 0; i < 8; i++)
  {
    if (arr[i] != '0')
      return 0;
  }
  return 1;
}

If you want a more elegant solution, have a look at iharob or Sourav's answers

like image 28
Eregrith Avatar answered Nov 09 '22 02:11

Eregrith


{'0','0','0','0','0','0','0','0'}

is called (and used as) a brace enclosed initializer list. This cannot be used for comparison anywhere.

You can make use of memcmp() to achieve this in an elegant way.

Pseudo-code

if (!memcmp(array, "00000000", 8))
{
   break;
}
like image 44
Sourav Ghosh Avatar answered Nov 09 '22 03:11

Sourav Ghosh