[英]How to input for arrays I don't know the length of?
我正在嘗試制作一個程序,接受參加考試的學生人數,以及他們每個人得到多少分。 我嘗試循環輸入,但它在 output 中給出看似隨機的數字
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int studenti;
scanf("%d", &studenti);
printf("%d ", studenti);
int niza[studenti];
for (int i = 1; i <= studenti; i++){
scanf("%d", &niza[i]);
i++;
printf("%d ",niza[i]);
}
}
我究竟做錯了什么? 有沒有另一種方法可以在不知道數組有多大的情況下添加數組元素,因為我在我的 uni 網站上通過檢查時不知道它們有多大。
主要問題是for
循環從1
開始並繼續到i <= studenti
。 在 C 中,arrays 以索引“0”開頭,此示例中的最終索引為studenti - 1
。
另一個問題是for
循環遞增i
並且有一個i++;
在循環體中。 i
增加了兩次。
檢查scanf
的返回。 它返回成功掃描的項目數。 此處為 1、0 或 EOF。
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int studenti = 0; // initialize
if ( 1 == scanf("%d", &studenti)) { // successful scan
printf("%d ", studenti);
int niza[studenti]; // variable length array
for (int i = 0; i < studenti; i++) { // start from index 0
if ( 1 == scanf("%d", &niza[i])) {
printf("%d ",niza[i]);
}
else { // scanf returned 0 or EOF
fprintf ( stderr, "problem scanning array element\n");
return 2;
}
}
}
else { // scanf returned 0 or EOF
fprintf ( stderr, "problem scanning\n");
return 1;
}
printf("\n");
return 0;
}
如果您不知道長度,您可能應該創建一個鏈表而不是 static 數組,並為每個學生創建另一個列表元素malloc
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.