I'm making a function which reverses a string and checks if the string is a palindrome or not. When I test the function with a obvious palindrome like "abba", the function says it's not a palindrome. Also the forward string and the reversed string also differ in string length!
#include <stdio.h>
#include <string.h>
char forward [] = "abba"; //The string to be reversed
int size = (sizeof(forward)/sizeof(forward[0]) - 1);
int j = 0;
char reverse [10];
void reverser(char forward []) {
printf("%s", "String forward: ");
for (int i = 0; i < size; i++) { //Function for printing out the forward string.
printf("%c", forward[i]);
}
printf("\n");
printf("%s", "String reversed: ");
for (int i = size, j = 0; i >= 0; --i, ++j) { //Function for reversing the string and printing it.
reverse[j] = forward[i];
printf("%c", reverse[j]);
}
printf("\n");
if (strcmp(forward, reverse) != 0) { //Using strcmp to check if the forward and reversed string are the same.
printf("Not a palindrome!\n");
}
else{
printf("A palindrome!\n");
}
printf("Forward string length: %d\n",strlen(forward));
printf("Reversed string length: %d\n",strlen(reverse));
}
int main () {
reverser(forward);
}
Output:
String forward: abba
String reversed: abba
Not a palindrome!
Forward string length: 9
Reversed string length: 0