Search code examples
c++strcmp

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


for some reason strcmp() isn't returning 0 as it should. Here is the code:

#include <iostream>
#include <ccstring>

int main()
{
      char buffer[2];
      buffer[0] = 'o';

      char buffer2[2];
      char buffer2[0] = 'o';

      cout<<strcmp(buffer, buffer2);
}

Thanks!


Solution

  • Terminated the string first before comparing.

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

    Edit:(March 7, 2014):
    Additional string initialization:

        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
    
        }