2015-11-28 35 views
-1

所以我有一個項目出現了分段錯誤,我不知道爲什麼。該項目將創建一個二維矩陣字拼圖,並根據輸入搜索單詞。我可以很容易地找到從左到右,從右到左的單詞,但是當我添加自上而下和從下到上的函數時,無論發生什麼,我都會遇到細分故障!我會附上我的代碼,使人們可以看到這個問題可能是什麼:有人可以解釋爲什麼我得到分段錯誤嗎?

//Checking for the first letter before going to sub categories 
void checkForWord(char *str, char **puzzle, int rows, int columns) { 
     int r,c,i=0; 

     for(r = 0; r < rows; r++) { 
      for(c = 0; c < columns; c++){ 
      if(puzzle[r][c] == str[i]) { 
       if(c != columns) { 
        if(puzzle[r][c+1] == str[i+1]) { 
         if(restOfWordLR(str, puzzle, r, c+1, 2) == 1) { 
          lrCount++; 
          totalCount++; 
          printf("TesT\n"); 
         } 
        } 
       } 
       if(c != 0) { 
        if(puzzle[r][c-1] == str[i+1]) { 
         if(restOfWordRL(str, puzzle, r, c-1, 2) == 1) { 
          rlCount++; 
          totalCount++; 
         } 
        } 
       } 
       if(r != rows) { 
        if(puzzle[r+1][c] == str[i+1]) { 
         if(restOfWordTB(str, puzzle, r+1, c, 2) == 1) { 
          tbCount++; 
          totalCount++; 
         } 
        } 
       } 
       if(r != 0) { 
        if(puzzle[r-1][c] == str[i+1]) { 
         if(restOfWordBT(str, puzzle, r-1, c, 2) == 1) { 
          btCount++; 
          totalCount++; 
         } 
        } 
       } 
      } 
     } 
    } 
} 
+0

請重新發布代碼。 –

+2

引用的代碼不會編譯,請閱讀[this](http://stackoverflow.com/help/mcve),並確保發佈完整的錯誤消息和堆棧跟蹤(如果有)。 –

回答

2
if(c != columns) { 
    if(puzzle[r][c+1] == str[i+1]) { 

這仍然獲得了數組邊界時c == columns-1,其中c != columns的,但c+1 == columns仍然是出界。

同樣的問題也發生在if(r != rows)代碼塊上。

您可以將它們更改爲if (c < columns-1)。修改後請務必查看邏輯的正確性。

+0

同樣在下一個塊: if(r!= rows){puzzle [r + 1] [c] ... – Jalai

+0

因此,我應該如何解決它?因爲我試圖將其更改爲 –

+0

@AdamAlred添加了可能的修復方法 – timrau

相關問題