简体   繁体   中英

Why is this code failing in c?

I'm trying to loop a 2D array, but for some reason the statement:

var = matrix[i + 1][j] // Fails for i = 1 and j = 0

BUT

next = i + 1; var = matrix[next][j] // Works, why???..

I think it should works because if i equals one and I add 1 it's 2, and I know that value is not empty, at least in my case, oh one thing to mention is that I'm testing with the following inputs: >4 4 1, meaning a 4x4 matrix with 1 rotation, so I am sure for a fact that matrix[2][0] is not empty and I can print it and access to it and all.

Here's the whole code:

#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;
   }
    matrix[i + 1] = high;

这是问题所在,我不见了[j],Visual Studio没有抛出异常,这就是为什么我不知道发生了什么的原因,但是使用GCC编译器并检查警告可以帮助我了解我在做什么。做错了,谢谢!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM