我有以下代码,仅显示第二行两次。不知道为什么。我的输入是1 4 5 2 3 0,而我的输出是2 3 0 2 3 0。所以下面是我的代码,我想请用户输入行数和列数。然后,用户输入元素以填充数组。最后一步是要打印出数组。
#include <stdio.h>
//#define ROW_SIZE 2
//#define COL_SIZE 3
int ROW_SIZE = 0;
int COL_SIZE = 0;
int main()
{
int matrix[ROW_SIZE][COL_SIZE];
int row;
int col;
printf("\n Enter the number of columns and rows: ");
scanf("%d %d", &ROW_SIZE, &COL_SIZE);
printf("Enter elements in matrix of size %dx%d \n", ROW_SIZE, COL_SIZE);
/* Outer loop to iterate through each row */
for(row=0; row<ROW_SIZE; row++)
{
/* Inner loop to iterate through columns of each row */
for(col=0; col<COL_SIZE; col++)
{
/* Input element in array */
scanf("%d", &matrix[row][col]);
}
/*
* Print all elements of array
*/
printf("\nElements in matrix are: \n");
for(row=0; row<ROW_SIZE; row++)
{
for(col=0; col<COL_SIZE; col++)
{
printf("%d", matrix[row][col]);
}
printf("\n");
}
return 0;
}
您不能声明具有0个元素的可变长度数组。
int ROW_SIZE = 0;
int COL_SIZE = 0;
int main()
{
int matrix[ROW_SIZE][COL_SIZE];
//...
您必须在输入ROW_SIZE和COL _SIZE的值后声明数组。
printf("\n Enter the number of columns and rows: ");
scanf("%d %d", &ROW_SIZE, &COL_SIZE);
int matrix[ROW_SIZE][COL_SIZE];
//...
此外,在文件作用域中定义变量ROW_SIZE和COL_SIZE也没有意义。最好在函数main的块范围内定义它们。
也有错字。您忘记了外循环的右括号
/* Outer loop to iterate through each row */
for(row=0; row<ROW_SIZE; row++)
{
/* Inner loop to iterate through columns of each row */
for(col=0; col<COL_SIZE; col++)
{
/* Input element in array */
scanf("%d", &matrix[row][col]);
}
真正解决问题的是移动此代码块。
int matrix[ROW_SIZE][COL_SIZE];
在这段代码下看起来像这样
`int main()
{
int matrix[ROW_SIZE][COL_SIZE];
int row;
int col;
`printf("\n Enter the number of columns and rows: ");
scanf("%d %d", &ROW_SIZE, &COL_SIZE);`