Search code examples
cstringpalindromestrcmpreversing

C: Palindrome: Different strlen-values


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


Solution

  • In this loop

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

    forward[i] is the terminating zero of the string when the initial value of variable i is equal to size

    Try the following loop implementation

    for ( int i = size, j = 0; i != 0; ++j) { //Function for reversing the string and printing it.
        reverse[j] = forward[--i];
        printf("%c", reverse[j]);       
        }
    

    Also take into account that for variables that will store values returned by the operator sizeof or by the function strlen it is better to use type size_t.

    So in these statements

    printf("Forward string length: %d\n",strlen(forward));
    printf("Reversed string length: %d\n",strlen(reverse));
    

    use format specifier %zu instead of %d

    For example

    printf("Forward string length: %zu\n",strlen(forward));
    printf("Reversed string length: %zu\n",strlen(reverse));
    

    Some answerers here said that you have to zero-terminate the string reverse. However it is already zero-terminated because it is declared outside any function and as result has the static storage duration and as such it is zero-initialized by default.