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