Reversing a string with strrev - C

Arlind picture Arlind · Jun 5, 2013 · Viewed 59.9k times · Source

I'm trying to reverse a string using the function strrev(). I know that strrev returns a pointer to the reversed string so I simply initialize an already allocated string with same size as the original one with the strrev function return. Obviously this isn't the correct way to do it and I get an "incompatible types" error in that line.

Here's the code:

int ispalindrome(int n)
{
   char s[10], sr[10];

   itoa(n, s, 10);

   printf("%s", s);

   sr = strrev(s);

   printf("\nReverse: %s", sr);

   if(strcmp(s, sr) == 0)
       return 1;

   else
       return 0;

}

Answer

user529758 picture user529758 · Jun 5, 2013
sr[10];
sr = strrev(s);

This doesn't even compile - arrays are not assignable. Post real code.

(You need to declare sr as char *sr for this to actually compile at all.)


Apart from that, your issue is that strrev() reverses the string in place, so the two strings will always compare equal (since you're effectively comparing the reversed string with itself). What you have to do is:

  • superfluously inefficient way: create a copy of the string, strrev() that, then strcmp() the original and the copy.

  • Somewhat more optimized approach for non-empty strings:


int ispal(const char *s)
{
    const char *p = s + strlen(s) - 1;
    while (s < p)
        if (*p-- != *s++)
            return 0;

    return 1;
}