简体   繁体   English

如何检查数组的内容?

[英]How do I check the contents of an array?

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? 我该怎么做呢?

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);

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的答案

{'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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM