0

I am trying to make a program in c where it can identify if a string is equal to its reverse or not.

#include <stdio.h>
#include <string.h>
#include <conio.h>
int main(){
    char str1[10] = "Hello";
    if (str1 == strrev(str1)){
        printf("True");
    }
    else{
        printf("False");
    }
getch();
return 0;
}

According to my knowledge, it should print False but it is printing True instead. Can anyone fix this issue. Thanks

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Faiyaz Ahmad
  • 87
  • 1
  • 6
  • In your own words, what do you expect to happen when you compare two `char*` values using `==`? Also, did you try reading the documentation for `strrev`? – Karl Knechtel Feb 12 '21 at 11:45
  • Read [How do I properly compare strings in C?](https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c), then write a program checking if two strings are the same. Once you got that working, moving on to the reverse scenario. – Lundin Feb 12 '21 at 12:00

3 Answers3

3

It seems the function strrev does not create a new character array. It reverses a string in place. So in this if statement

if (str1 == strrev(str1)){

there are compared two pointers to the first element of the same character array str1.

To compare two strings use the standard C function strcmp. For example

char str1[10] = "Hello";
char str2[10];

strcpy( str2, str1 );

if ( strcmp( str1, strrev(str2) ) == 0 ){
    printf("True");
}
else{
    printf("False");
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

If you use the operator == you are just comparing the str1 memory address pointer with itself, and of course the result is true, despite the fact that the strrev modifies the array. As already said by previous answers, you should create a copy of the character array str1 and than using strcmp to compare the two arrays.

Marco Tizzano
  • 1,726
  • 1
  • 11
  • 18
0

I think it's worth pointing out that it's possible to check for palindromes without having to create a copy of the original string. This would result in code that works faster and uses less memory.

#include <stdio.h>
#include <string.h>

int is_palindrome(const char *s) {
    int n = strlen(s);
    for (int i=0; i < n--; i++) {
        if (s[i] != s[n]) return 0;
    }
    return 1;
}

int main() {
    char *s1 = "racehorse";
    char *s2 = "racecar";
    printf("'%s' %s a palindrome\n", s1, is_palindrome(s1) ? "is" : "is not");
    printf("'%s' %s a palindrome\n", s2, is_palindrome(s2) ? "is" : "is not");
    return 0;
}
r3mainer
  • 23,981
  • 3
  • 51
  • 88