首页 > 解决方案 > Why does my code print out some garbage from my array?

问题描述

I am currently learning C, and I want to create a function that reverses an input. Here is the piece of code I wrote:

#include <stdio.h>

int main(int argc, char** argv) {
char input[100];

while(1) {
    fgets(input, 100, stdin);

        for(int i = 99; i > -1; i--) {
            printf("%c", input[i]);
        }

    printf("\n");
    }
}

The output of this is correct, but it also prints some garbage in between and I don't understand why. Can someone explain this to me?

This is the output:

enter image description here

标签: cstringstdout

解决方案


Firstly, you should clear memory before using it.

Secondly, always keep one char with 'NULL' value at the end of a string. (only an option for your case, because you are not using sprintf, strcpy... and so on.)

Thirdly the for loop should start at the end of the input, that is strlen(input) which is located on <string.h>

#include <stdio.h>
#include <string.h>

int main(int argc, char** argv) {
char input[100];

while(1) {
    memset(input, 0, sizeof(input));    // add memset() to clear memory before using it
    fgets(input, 100, stdin);

    for(int i = strlen(input); i > -1; i--) {
        printf("%c", input[i]);
    }

    printf("\n");
    }
}

推荐阅读