Search code examples
ccomparefgetsstrcmp

strcmp() thinks that strings arent equal.. but are they?


For unknown reason, result of running my C program is quite unexpected. I think that it has to be some kind of a beginner mistake, however I can't find out really, where is it.

#include <stdio.h>
#include <string.h>
int main()
{
char string1[50];
char string2[50];
int compare;

puts("Enter two strings: ");
fgets(string1, strlen(string1)+1, stdin);
fgets(string2, strlen(string2)+1, stdin);

compare=strcmp(string1, string2); /* usage of extra variable makes the code more readable but wastes more memory */

printf("%d: ",compare);

if (compare<0) puts("First string is lesser");
else if (compare>0) puts ("First string is bigger");
     else puts("Strings are equal");


return 0;
  }

And on testing:

Enter two strings: 
heheisntthisalongstring
heheisntthisalongstring
1: First string is bigger


------------------
(program exited with code: 0)
Press return to continue

Shouldn't those strings be equal?


Solution

  • fgets(string1, strlen(string1)+1, stdin);
    fgets(string2, strlen(string2)+1, stdin);
    

    These are wrong. string1 and string2 are not initialized, and strlen just counts the number of bytes, till hitting \0. In this case, strlen could return any (random non-negative) number.

    Use sizeof, instead of strlen here.