注意:这是一道作业题。
Use FOR construction to fill 2D board with values that were given by user. The program asks for board size n, m and then it asks for each board value.
我的尝试
#include <stdio.h>
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
}
}
}
错误:c:13 可变大小对象可能未初始化
编辑:
#include <stdio.h>
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]);
编辑:
您正在使用 variable length array (VLA)在你的程序中:
int r[i][y];
因为 i
和 y
不是常量而是变量。 VLA 是 C99 标准功能。
关于c - 如何用用户输入值填充 C 中的二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8211087/