문제

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;

}
도움이 되었습니까?

해결책

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

다른 팁

OK, did some research and looks like strrev is not available in Linux (if that is your platform); check out Is the strrev() function not available in Linux?

You can use the alternative implementation suggested therein or use the answer by @H2CO3.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top