strcmp 仅在循环开始时起作用

strcmp only works at the start of a loop

我一直在尝试创建一个简单的程序来循环遍历数组的成员并扫描字符以查找一组特定的字符。我有 运行 问题,其中 strcmp() 仅在循环开始时有效。我正在努力理解为什么会发生这种情况,我们将不胜感激。

char *file[3] = {"!x", "!!x", "x!"};

for (int i = 0; i < sizeof(file) / sizeof(file[0]); i++) {
  char *line = file[i];
  printf("\n");
  for (int i = 0; i < strlen(line); i = i + 1) {
    char character = line[i];
    if (strcmp("!", &character) == 0) {
      printf("[YES] %c\n", character);
    } else {
      printf("[NO] %c\n", character);
    }
  }
}

输出

[YES] !
[NO] x

[YES] !
[NO] !
[NO] x

[NO] x
[NO] !

strcmp 函数需要空终止字符串的地址。相反,您将 char 的地址传递给它。 strcmp 然后尝试读取超过 character 的内存位置,导致 undefined behavior

然而,真正的问题是您不想比较字符串。你要比较字符。

if (character == '!') {

strcmp() 比较空终止字符串。在代码中:

char character = line[i];
if (strcmp("!", &character) == 0) 

character 不是以 null 结尾的字符串。它能起作用完全是偶然的。

您需要更多类似的东西来比较字符串:

char character[2] = { line[i], '[=11=]' };
if (strcmp("!", character) == 0) 

或者像这样比较字符:

char character = line[i];
if (character == '!') 

这里的问题是,您向 strcmp() 提供了错误的参数,&character 不是指向 string.[=21 的指针=]

引用 C11,章节 int strcmp(const char *s1, const char *s2);

int strcmp(const char *s1, const char *s2);

The strcmp function compares the string pointed to by s1 to the string pointed to by s2.

因此,它希望两个参数都是 string 类型,而在您的情况下则不是。

你可以简单地使用比较运算符==来比较chars,比如

 if (line[i] == '!')  //notice the '' s, they are not ""s

等等。