簡體   English   中英

為什么NULL條件在3個字符后終止

[英]why does NULL condition terminate after 3 chars

我寫了這個函數,該函數應該將一個字符串讀入一個數組,直到NULL char為止,該字符代表該行中字符串的結尾。 但這不怎么奏效。

int main(void){
    int MAX = 39;
    char number1[MAX + 1];
    int i;

    read_array(number1, MAX);

    for(i = 0; i <= MAX; i++)
        printf("%c", number1[i]);

    return 0;
}

int read_array(char* number, int size) {
    printf("\nEnter an integer number at a maximum of 39 digits please.\n");

    int result = 0;
    char* i;
    for (i = number; *i != NULL; i++)
        scanf("%c", i);

    return result;
}

無論我鍵入多少個字符,當我打印結果時,它只會給我前3個字符,我也不知道為什么。 任何想法? 謝謝

如前所述, scanf不會為您的字符串以空值終止。 如果您要閱讀直到用戶按下回車鍵,請進行檢查。 您可以通過以下方式將for循環替換為do-while循環:

do {
    scanf("%c", i); // read the data into i *before* the loop condition check
} while (*i++ != '\n'); // check for '\n' (unless you expect the user to
                        // actually type the null character)

關於i指向垃圾內存的@NedStark點是正確的。 number1的數據永遠不會初始化,因此只會充滿垃圾。 您的循環條件( *i != NULL )是 scanf調用之前檢查的,這意味着循環條件只是檢查舊的垃圾數據(而不是正確的值)。

問題出在你的循環中

for (i = number; *i != NULL; i++)
    scanf("%c", i);

在遞增i之后,i指向包含垃圾數據的下一個內存位置,因為尚未正確初始化它。 可能您想要類似:

char c;
i = number;
do
{
    scanf("%c", &c);
    *i = c;
    ++i;
} while (c!='\n')
*i = '\0';

暫無
暫無

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

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