如何检查数组的内容?

时间:2021-09-27 01:08:40

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

我想检查一个char数组是否包含所有'0'。

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?

我该怎么做呢?

3 个解决方案

#1


7  

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

您可以像这样将值与memcmp()进行比较

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

#2


6  

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

如果您想要更优雅的解决方案,请查看iharob或Sourav的答案

#3


5  

{'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.

您可以使用memcmp()以优雅的方式实现此目的。

Pseudo-code

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

#1


7  

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

您可以像这样将值与memcmp()进行比较

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

#2


6  

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

如果您想要更优雅的解决方案,请查看iharob或Sourav的答案

#3


5  

{'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.

您可以使用memcmp()以优雅的方式实现此目的。

Pseudo-code

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