如何用用户输入值填充C中的2D数组? [英] How to fill a 2D array in C with user input values?
本文介绍了如何用用户输入值填充C中的2D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
注意:这是一个家庭作业问题.
Note: This is a homework question.
使用FOR构造将2D板的值填充为用户.程序要求输入电路板尺寸n,m,然后要求每一个板值.
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
获取要读取的变量的地址,并返回读取的项目数.它不会返回读取的值.
scanf
takes the address of the variable that is being read and returns the number of items read. It does not return the value read.
替换
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];
as i
和 y
不是常量,而是变量.VLA是C99的标准功能.
as i
and y
are not constants and are variables. VLA are a C99 standard feature.
这篇关于如何用用户输入值填充C中的2D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文