簡體   English   中英

為什么我的代碼會從數組中打印出一些垃圾?

[英]Why does my code print out some garbage from my array?

我目前正在學習C,並且我想創建一個反轉輸入的函數。 這是我寫的代碼:

#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");
    }
}

這樣的輸出是正確的,但是它還會在中間輸出一些垃圾,我不明白為什么。 誰可以給我解釋一下這個?

這是輸出:

在此處輸入圖片說明

首先,您應該在使用之前清除內存。

其次,始終在字符串末尾保留一個帶有'NULL'值的字符。 (這只是您的情況的一個選擇,因為您沒有使用sprintfstrcpy ...等。)

第三, for循環應從輸入的末尾開始,即位於<string.h>上的strlen(input)

#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");
    }
}

Yuanhui解釋的很好,因此我將對他的代碼進行一些改進:

int main() { // No need for argc and argv unless you use them
char input[100] = {0}; // Simpler than memset

do {
    // Security risk if you decide to change the size of input, so use
    // sizeof input instead of hard coded value. Also, check return value.
    if(!fgets(input, sizeof input, stdin)) { /* Error handling code */ }

    // Overkill to use printf for a single char
    for(int i = strlen(input); i > -1; i--) putchar(input[i]);
    putchar('\n');
} while(!feof(stdin)) // End the loop on EOF
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM