c - 从 scanf 输入值但打印不同的值
问题描述
我从 scanf 输入值,但是当我打印它们时,所有列都有最后一行的值。
#include <stdio.h>
int main(){
int N, M;
int A[N][M];
int T[N][M];
int i,j;
printf("Insert number of rows and columns: ");
scanf("%d %d",&N,&M);
printf("\nInsert the matrix\n");
for(i=0; i<N; i++){
for(j=0; j<M; j++){
scanf("%d", &A[i][j]);
}
}
printf("\nInserted matrix:\n");
for(i=0; i<N; i++){
for(j=0; j<M; j++){
printf("%d ",A[i][j]);
}
printf("\n");
}
return 0;
}
我试过检查它是否是索引问题并用它的坐标打印每个元素,但这似乎很好,问题必须在scanf中的某个地方。输入:
Insert number of rows and columns: 3 3
Insert the matrix
1 2 3
4 5 6
7 8 9
输出:
Inserted matrix:
7 8 9
7 8 9
7 8 9
解决方案
打开编译器警告。任何体面的编译器都会警告您:
int N, M;
int A[N][M];
N
并且M
没有被初始化。因为它们没有初始化,所以你不知道int A[N][M];
会做什么。到达声明时,必须知道数组维度。
您可以在读取and之后移动int A[N][M];
and 。int T[N][M];
scanf
N
M
请注意,声明具有可变长度的数组不适用于通用代码。它可以用于简单的学校作业,但您最终应该会进步到使用malloc
和其他技术。(可变长度数组也可以用于已知大小在一定范围内的情况。)
推荐阅读
- c - 为什么 C 中的 signal() 函数只能工作一次
- java - 如何在 Android Studio 中显示屏幕尺寸(简单方式)?
- reactjs - 如何在 ReactJs 中更改 img src onmouseover
- javascript - 如何找到在按钮单击以使用 selenium 抓取它时播放的音频文件的位置
- docusignapi - 在文件末尾添加签名
- r - 如何使用循环更新前向选择的公式
- regex - 如何删除 || 使用记事本++上的正则表达式从字符串末尾的表达式?
- grep - 为什么 PCRE grep 将正斜杠视为空格?
- kubernetes - 如何从 ArgoCD CLI 添加外部集群进行部署
- c# - 如何使用 Entity Framework Core 将实体类定义为跨多个实体共享的集合?