首页 > 解决方案 > 从 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

标签: cmatrix

解决方案


打开编译器警告。任何体面的编译器都会警告您:

int N, M;
int A[N][M];

N并且M没有被初始化。因为它们没有初始化,所以你不知道int A[N][M];会做什么。到达声明时,必须知道数组维度。

您可以在读取and之后移动int A[N][M];and 。int T[N][M];scanfNM

请注意,声明具有可变长度的数组不适用于通用代码。它可以用于简单的学校作业,但您最终应该会进步到使用malloc和其他技术。(可变长度数组也可以用于已知大小在一定范围内的情况。)


推荐阅读