2017-08-04 93 views
0

我試圖循環二維數組,但由於某些原因的聲明:爲什麼這個代碼在c中失敗?

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

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

我認爲它應該工作,因爲如果我等於一個和我加1是2 ,並且我知道價值並不是空的,至少在我的情況下,有一點要提到的是我正在測試以下輸入:> 4 4 1,這意味着一個4x4的矩陣和一個旋轉,所以我確定矩陣[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; 
    } 
+2

請解釋什麼是「失敗」? –

+0

內存訪問衝突 – user3044096

+2

@ user3044096使用調試器進入代碼,找到導致崩潰的行,跟蹤變量中的值並檢查是否有可疑內容。 –

回答

0
matrix[i + 1] = high; 

這條線的問題,我缺少[J],Visual Studio中沒有拋出異常,這就是爲什麼我無法知道是什麼正在發生,但使用GCC編譯器並檢查警告幫助我瞭解我做錯了什麼,謝謝!