user3367265
user3367265

Reputation: 41

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!

Upvotes: 0

Views: 208

Answers (2)

acegs
acegs

Reputation: 2809

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

    }

Upvotes: 0

Karoly Horvath
Karoly Horvath

Reputation: 96266

C strings are zero terminated.

Your strings aren't. This is simply undefined behaviour. Anything can happen.

Upvotes: 6

Related Questions