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!!!
'\0'to the end of the string. This is required for c-strings.