0

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!!!

2
  • 1
    You are probably forgetting to add a '\0' to the end of the string. This is required for c-strings. Commented Mar 12, 2024 at 18:24
  • PSA: "It seems to happens randomly" is often a sign of undefined behaviour. Commented Mar 12, 2024 at 18:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it worked! I will now try to make it without a second array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.