0
Well, I have the code below that should reverse a string and show if it is a palindrome. However, when the word has an even number of characters the result is wrong. I think the error is in the third for, can anyone see any problem? Below is an example of the output with the palindrome "that".
#include <stdio.h>
#include <string.h>
#define SIZE 21
int main (){
char palavra[SIZE];
int last;
printf("Digite a palavra: ");
scanf("%s", palavra);
for (int i = 0; palavra[i] != 0; ++i) { // determina o fim da string
last = i + 1;
}
char palavraReduzida[last], palavraInvertida[last]; // cria duas strings, uma com seu tamanho real e outra que vai ser invertida
for(int i = 0; i <= last; ++i){
palavraReduzida[i] = palavra[i]; //adiciona os caracteres a string de tamanho real
}
for(int i = 0; palavraReduzida[i] != 0; ++i) {
palavraInvertida[i] = palavraReduzida[last - 1]; // Inverte a string
--last;
}
printf("%s %d %s %d\n", palavraReduzida, sizeof(palavraReduzida), palavraInvertida, sizeof(palavraInvertida)); //Escreve a string invertida e a string de tamanho
if(strcmp(palavraReduzida, palavraInvertida) == 0) //Compara as strings //Também mostra os tamanhos
printf("E um palindromo");
else
printf("Nao e um palindromo");
return 0;
}
And you have to do it all for some reason or you can do it simpler. https://answall.com/q/192842/101
– Maniero
True, it helped a lot, thank you! But anyway, you would know why at the end of the inverted string appear this unexpected character?
– Pedro Vinicius
Why you failed to add the ending character ' 0'.
– anonimo
Good evening! Why not use the strrev() function to invert your string? It is inside the string library.h... It would make your resolution much easier.
– Prof Tiago Gonçalves