【发布时间】:2017-08-04 18:52:13
【问题描述】:
我正在尝试循环一个二维数组,但由于某种原因,声明:
var = matrix[i + 1][j] // Fails for i = 1 and j = 0
但是
next = i + 1; var = matrix[next][j] // Works, why???..
我认为它应该可以工作,因为如果 i 等于 1 并且我加 1 它是 2,并且我知道该值不为空,至少在我的情况下,哦,要提的一件事是我正在使用以下输入进行测试:>4 4 1,表示一个 4x4 矩阵,旋转 1 次,所以我确信 matrix[2][0] 不是空的,我可以打印它并访问它。
这是完整的代码:
#include <stdio.h>
#include <stdlib.h>
void rotateMatrix(int** matrix, int top, int right, int left, int bottom)
{
//int rows = right;
//int columns = bottom;
int rowScan = 0;
int columnScan = 0;
int high = 0;
int low = 0;
int test = matrix[2][0];
for (int i = 0; rowScan != 1;)
{
for (int j = 0; columnScan != 1;)
{
//int next = i + 1;
high = matrix[i + 1][j]; //FAILS HERE WHEN
matrix[i + 1][j] = low != 0 ? low : matrix[i][j];
i++;
if (i >= bottom)
{
bottom--;
break;
}
if ((i + 1) < bottom)
{
low = matrix[i + 1][j];
matrix[i + 1] = high;
}
if ((i + 1) == bottom)
{
columnScan = 1;
rowScan = 1;
}
}
}
}
int main()
{
//-- Declaring variables
int rows, columns, rotations;
//-- Initializing variables
rows = 0;
columns = 0;
rotations = 0;
//-- Scanning parameters and adding them to the stdin buffer
scanf("%d %d %d", &rows, &columns, &rotations);
//-- Initializing 2D array to save the Matrix values allocating space in memory
int **matrix = (int**)malloc(rows * sizeof(int*));
//-- Initializing each allocated pointer to each column size
for (int i = 0; i < rows;i++)
matrix[i] = malloc(columns * sizeof(int));
//-- Scanning Matrix values and saving them into stdin buffer
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
matrix[i][j] = rand() % 10;
// scanf("%d", &matrix[i][j]);
//-- Rotating R times
while ((rotations--) != 0)
rotateMatrix(matrix, 0, columns, 0, rows);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
printf("%d", matrix[i][j]);
}
printf("\n");
}
getchar();
getchar();
return 0;
}
【问题讨论】:
-
请解释什么是“失败”?
-
@user3044096 使用调试器进入您的代码,找到导致崩溃的行,跟踪变量中的值并检查是否有任何可疑之处。
-
一方面,
matrix[i + 1] = high;显然是错误的。在 GCC 上,x.c:36:27: warning: assignment makes pointer from integer without a cast [-Wint-conversion] -
当指向数组的指针数组被描述为“二维”数组时,我立即感到怀疑:(
-
注意你的编译器警告。阅读警告,理解它们,修复它们,运行你的程序,总是按照这个顺序。
标签: c arrays multidimensional-array ansi-c