Search code examples
cc-stringsreversing

Last character index of inverted string in C being the whole uninverted original string


I just started learning C and i'm trying to write a program that inverts the string so that furthermore i can check if the string is a palindrome. I did it by adding a for loop limited by the size of the original string i'm trying to revert, the size number decrease. And then each number of that size num access the index of the original str and appends it to a new str variable. This go perfectly until it reaches the last character, thats when it adds a unknown symbol to the new str and insert the whole original string to it.

DETAIL: It seems to happens randomly, i don't know what's the problem.

this is my code

#include <stdio.h>

int main ( void ) {
char main_str[] = "lizard";
char inv_str[sizeof(main_str)];
int index = 0;

for (int inv_index = sizeof(main_str)-2;inv_index >= 0;inv_index--) {
    inv_str[index] = main_str[inv_index];
    index++;
}
printf("%s",inv_str);

}

when i set the str as "palindrome", it outputs a sucessfully reverted string. However, when i add the word "lizard", for example, this is the output: I'm using the exact same code!!!


Solution

  • The destination array inv_str does not contain a string because you forgot to append copied characters of the source array with the terminating zero character '\0'.

    Either declare the array like

    char inv_str[sizeof(main_str)] = { 0 };
    

    initially setting all its characters to zero or insert the terminating zero character like

    inv_str[sizeof( inv_str ) - 1] = '\0';
    

    In general the approach with using the operator sizeof with a character array is incorrect because an array can contain a string that does not occupy all characters of the array. It is better to use standard string function strlen when characters of the source array are copied in the destination array..

    Pay attention to that to check whether a string is a palindrome there is no need to create an auxiliary attay.