为什么 strcmp() 没有像我应该的那样工作?C++

Why isn't strcmp() working as I though it should? c++

本文关键字:工作 C++ 我应该 strcmp 为什么      更新时间:2023-10-16

由于某种原因,strcmp() 没有像它应该的那样返回 0。这是代码:

#include <iostream>
#include <ccstring>
int main()
{
      char buffer[2];
      buffer[0] = 'o';
      char buffer2[2];
      char buffer2[0] = 'o';
      cout<<strcmp(buffer, buffer2);
}

谢谢!

C 字符串以零结尾。

你的字符串不是。这简直是未定义的行为。任何事情都可能发生。

在比较之前先终止字符串。

    #include <iostream>
    #include <ccstring>
    int main()
    {
          char buffer[2];
          buffer[0] = 'o';
          buffer[1] = 0;  <--
          char buffer2[2];
          buffer2[0] = 'o';
              buffer2[1] = 0;  <--
          cout<<strcmp(buffer, buffer2);
    }

编辑:(2014年3月7日):
其他字符串初始化:

    int main()
    {
          //---using string literals.
          char* str1  = "Hello one";   //<--this is already NULL terminated
          char str2[] = "Hello two";  //<--also already NULL terminated.
          //---element wise initializatin
          char str3[] = {'H','e','l','l','o'};  //<--this is not NULL terminated
          char str4[] = {'W','o','r','l','d', 0}; //<--Manual NULL termination
    }