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?
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.
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);
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
{'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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With