【问题标题】:strcmp only works at the start of a loopstrcmp 仅在循环开始时起作用
【发布时间】:2016-09-20 21:09:15
【问题描述】:

我一直在尝试创建一个简单的程序,该程序循环遍历数组的成员并扫描字符以查找特定的字符。我遇到了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] !

【问题讨论】:

  • 为什么要使用字符串比较函数来比较单个字符
  • 你可能有未定义的行为:没有什么能保证 char 上的指针在附近某处为零,因为它不是字符串。
  • 这里关于需要空终止字符串的 cmets 当然是正确的。这种行为看起来仍然很奇怪,因为在这种情况下,我们知道&amp;character 之后的内容,因为我们知道字符串中的其余字符。我不清楚为什么它会以这种特定方式行为不端。

标签: c arrays string char strcmp


【解决方案1】:

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

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

if (character == '!') {

【讨论】:

    【解决方案2】:

    这里的问题是,您向strcmp() 提供了错误的参数,&amp;character 不是指向 字符串 的指针。

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

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

    strcmp 函数将s1 指向的字符串与s1 指向的字符串进行比较 s2.

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

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

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

    等等。

    【讨论】:

      【解决方案3】:

      strcmp() 比较以空字符结尾的字符串。在代码中:

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

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

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

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

      或者像这样比较字符:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-06
        • 2020-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-30
        相关资源
        最近更新 更多