c - 如何用用户输入值填充 C 中的二维数组?

标签 c arrays

注意:这是一道作业题。

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];

因为 iy 不是常量而是变量。 VLA 是 C99 标准功能。

关于c - 如何用用户输入值填充 C 中的二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8211087/

相关文章:

python - c 函数的 Ctype 返回类型

用于初始化数组的 C++ 语法

java - java中 boolean 表达式如何工作?

c - 如何回调到 exe 中的函数?

c - 缩短长代码

c - 在 C 中释放一个双向链表

c++ - 防止 C 整数溢出

java - 如何通过类和方法传递数组和 int ?

java - 为什么我的 while 循环无法计算数组的总和并显示数组

javascript - 如何仅从数组中追加一次值