[英]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.