Search code examples
cpalindrome

Dont get the output out of char palindrom[]


i trying to make a palindrom out of the user input.

Im saving the user input as array in char eingabe[] with int i im counting the index of the used arrays.

Then i want to copy the reversed value of eingabe in palindrom and then printf both of them to get the palindrom.

My i and j are counting correctly, but i dont get the output for palindrom.

I hope you can help me.

#include <stdio.h>

int main(){
char eingabe[20];
char palindrom[20];
int i = 0;
int j = 0;  
char c;

do{
    c = getchar();
    if (c != EOF){
        eingabe[i] = c;
        i++;
    }
} while (c != EOF);

eingabe[i] = '\0';


do{ 
    palindrom[j] = eingabe[i];

    j++;
    --i;


} while (i != 0);

    palindrom[j] = '\0';

    printf("\n\n%s",eingabe);
    printf("%s\n\n",palindrom);

    return 0;
}

Solution

  • It is sometimes very helpful to add printf's to see what is going on. For example, if I add:

    do { 
        printf("palindrom[%d] = eingabe[%d]\n", j, i);
        palindrom[j] = eingabe[i];
    

    then the output is:

    abcde
    palindrom[0] = eingabe[5]
    palindrom[1] = eingabe[4]
    palindrom[2] = eingabe[3]
    palindrom[3] = eingabe[2]
    palindrom[4] = eingabe[1]
    eingabe:   "abcde"
    palindrom: ""
    

    The problem is immediately obvious: the array index is off by 1. Since the first character of palindrom ([0]) gets set to the last character of eingabe ([5]) which is "\0", then C sees it as an empty string.

    This is easily corrected by moving the --i to the top of the loop:

    do { 
        --i;
        palindrom[j] = eingabe[i];
        j++;
    } while (i != 0);