如何使用用户输入值填充C中的2D数组?
注意:这是一个家庭作业问题。
使用FOR构造来使用用户给出的值填充2D板。 程序要求板尺寸为n,m,然后询问每个板的值。
我的尝试
#include int main(){ printf("Enter the number of columns"); int i = scanf("%d",&i); printf("Enter the number of rows"); int y = scanf("%d",&y); int r[i][y]; int a; int b; for (a=0; a<i; a++){ for(b=0; b<y; b++){ int r[a][b] = scanf("%d",&a,&b); //bug } } }
Bug: c:13 variable-sized object may not be initialized
编辑:
#include int main(){ printf("Enter the number of columns"); int i; scanf("%d", &i); printf("Enter the number of rows"); int y; scanf("%d", &y); int r[i][y]; int a; int b; for (a=0; a<i; a++){ for (b=0; b<y; b++){ scanf("%d",&r[a][b]); } } }
scanf
获取正在读取的变量的地址,并返回读取的项目数 。 它不会返回读取的值。
更换
int i = scanf("%d",&i); int y = scanf("%d",&y);
通过
scanf("%d",&i); scanf("%d",&y);
和
int r[a][b] = scanf("%d",&a,&b);
通过
scanf("%d",&r[a][b]);
编辑:
您正在程序中使用可变长度数组(VLA) :
int r[i][y];
因为i
和y
不是常数,而是变量。 VLA是C99标准function。
您必须动态分配2D数组,因为您在编译时不知道它的大小。
更换
int r[i][y];
同
int *r = malloc(i*y*sizeof(int));
完成后,添加:
free(r);
*以及SCANF错误,人们已在此处回答。
首先, scanf
的返回值不是从stdin
读取的值,而是scanf
读取的输入值的数量。
其次,C不允许使用变量创建数组。 您必须首先通过动态分配它来创建一个数组。 对于第一个数组中的每个条目,您必须创建另一个数组。
别忘了释放你分配的记忆!
scanf(%d, &var)
的使用不正确。
scanf
从控制台读取一个整数(此类型由其第一个参数%d
指定)并将其存储在第二个参数中 。
第二个参数必须是指针 ,因此当您的变量不是指针时需要&
。
因此,您应该以这种方式更正您的代码:
int i; scanf("%d",&i); int y; scanf("%d", &y);
在你的for
循环中
scanf("%d", &r[a][b]);
由于行缓冲,它不会打印消息。
如果你将\n
添加到你的字符串(开始一个新行),它可能会做你期望的:
printf("Enter the number of columns\n");
或者,如果您确实希望用户在同一行上键入,则需要手动刷新缓冲区:
printf("Enter the number of columns"); fflush (stdout);