How to check the contents of an array?

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

I tried this, but it does not work:

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

How to do it?

+5
source share
3 answers

it

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

definitely wrong and certainly not compiled.

You can compare the values ​​with memcmp() as follows

 int allZeroes = (memcmp(array, "00000000", 8) == 0); 
+7
source

Actually

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

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, look at the answers from iharob or Sourav.

+6
source
 {'0','0','0','0','0','0','0','0'} 

a list of parenthesized lists enclosed in parentheses is called (and used as). This cannot be used for comparison anywhere.

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

Pseudo code

 if (!memcmp(array, "00000000", 8)) { break; } 
+5
source

All Articles