簡體   English   中英

如何在 C 編程中從用戶那里獲取數組的輸入?

[英]How do I get input for an array from a user in C programming?

我是 C 的新手,在用戶輸入數組時遇到了一些問題。

這是代碼

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int n, i;
    int score [n];
    printf("Number of scores: ");
    scanf("%d", &n);
    for(i=0; i<n; i++){
       printf("score: ");
       scanf("%d", &score[i]);
    }
    return 0;
}

我為 n 設置的值無關緊要。 它總是提示用戶 4 次。

正如評論中提到的,你必須改變這個:

/* bad */
int score [n];
printf("Number of scores: ");
scanf("%d", &n);

進入這個

/* good */
printf("Number of scores: ");
scanf("%d", &n);
int score [n];

這是因為 C 像閱讀書籍一樣從上到下執行代碼。 一旦用戶輸入它,它就不會在上面的幾行“加倍”並填寫n 在您聲明int score [n]時,必須已經知道n

如果您在編譯期間使用大小未知的數組,我建議使用 memory 分配。 因此用戶在運行程序時確定數組大小。

#include  <stdio.h>
#include <stdlib.h>

int main(void)
{
    int n, i;
    int *score;
    printf("Number of scores: ");
    scanf("%d", &n);

    score = (int *)malloc(sizeof(int)*n);

    for(i=0; i<n; i++){
       printf("score: ");
       scanf("%d", &score[i]);
    }
    free(score)
    return 0;
}

malloc function 分配大小為n的 memory 並返回指向分配的 ZCD69BZ7B697F0890D818D 的指針

暫無
暫無

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

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