Search code examples
cstringpalindromestrcmp

strcmp() returns 0 when comparing to unequal strings


In C, strcmp() function returns 0 if two strings are equal. When I give a code like this,

char str[10] = "hello";
if(strcmp(str,strrev(str))==0)
{
printf("1");
}
else
printf("0");

This should print a 1 if its a palindromic string or it should print 0 if it is not a palindrome. But it prints 1 even when the given string "hello" is not a palindrome. Where is the mistake?


Solution

  • strrev() is not a standatd C library function.

    Your strrev() is reversing the actual string str first, then going for strcmp() with the changed string. So the results are always equal.

    If you want to have the desired result:

    1. make a copy of the original string
    2. pass the original string to strrev()
    3. compare with the earlier copy.