Search code examples
creversec-stringsfunction-definition

C program outputs weird characters


Trying to print reversed input in C:

#include <stdio.h>

#define MAX_SIZE 100
/* Reverses input */
void reverse(char string[], char reversed[]);

int main() {
    char input[MAX_SIZE], output[MAX_SIZE + 1];
    char c;
    int index = 0;

    while ((c = getchar()) != '\n')
    {
        input[index] = c;
        ++index;
    }

    reverse(input, output);
    printf("%s\n", output);

}

void reverse(char string[], char reversed[]) {  
    int rev;
    rev = 0;

    for (int str = MAX_SIZE - 1; str >= 0; --str) {
        if (string[str] != '\0') {
            reversed[rev] = string[str];
            ++rev;
        }
    }
}

but have this weird result:

input:

abc

output:

?:? ????:???:?cba?

both input and output arrays comprise \0, so I guess there's some index out of bounds exception, but I can't find out where exactly. Thank you.


Solution

  • For the length of the original string you shouldn't use MAX_SIZE because that's the total size of the container, not the size of the string.

    Another problem is that the input string is not null terminated, and because of that it's not possible to know its length, unless you tracked the number of charaters read from stdin and passed it as an argument.

    Fixing these two main issues (along with some other minor problems (comments)) would make your code work:

    #include <stdio.h>
    #include <string.h>
    
    #define MAX_SIZE 100
    
    void reverse(const char string[], char reversed[]);
    
    int main()
    {
        char input[MAX_SIZE], output[MAX_SIZE]; // no need for the extra character
        char c;
        int index = 0;
    
        while ((c = getchar()) != '\n' && index < MAX_SIZE - 1) // avoid buffer overflow
        {
            input[index] = c;
            ++index;
        }
        input[index] = '\0'; // null terminate the original string
    
        reverse(input, output);
        printf("%s\n", output);
    }
    
    void reverse(const char string[], char reversed[])
    {
        int rev;
        rev = 0;
    
        // stop condition with the length of the string
        for (int str = strlen(string) - 1; str >= 0; --str)
        {
            reversed[rev] = string[str];
            ++rev;
        }
        reversed[rev] = '\0'; // null terminate the reversed string
    }