2011-12-19 189 views
0

我嘗試執行http://www.cprogramming.com/tutorial/game_programming/same_game_part1_p2.html中描述的遊戲。雖然它最初運行良好,但從運行的某一時刻起,在運行時崩潰,而構建並不表示出現任何錯誤。這個問題似乎是「處理異常」 - 上線未處理的異常

return m_arrColors[m_arrBoard[row][col]]; 

「訪問衝突讀取位置」的功能

COLORREF CSameGameBoard::GetBoardSpace(int row, int col) 
{ 
    // Check the bounds of the array 
if(row < 0 || row >= m_nRows || col < 0 || col >= m_nColumns) 
    return m_arrColors[0]; 
return m_arrColors[m_arrBoard[row][col]]; 
} 

任何可能的原因是什麼?

更新:

程序崩潰嘗試訪問

m_arrColors[m_arrBoard[0][0]]; 

m_arrColors和m_arrBoard首次由構造函數定義如下:我加入了:

CSameGameBoard::CSameGameBoard(void) 
    :m_arrBoard(NULL), 
    m_nColumns(15), m_nRows(15), 
    m_nHeight(35), m_nWidth(35) 
{ 
    m_arrColors[0] = RGB( 0, 0, 0); 
    m_arrColors[1] = RGB(255, 0, 0); 
    m_arrColors[2] = RGB(255,255, 64); 
    m_arrColors[3] = RGB( 0, 0,255); 
} 

UPDATE2命令SetupBoard();在構造函數的正文中,它起作用了。然而,它不是由教程http://www.cprogramming.com/tutorial/game_programming/same_game_part1_p2.html提出的,並且最初在我的程序中正常工作,但沒有它。

+1

什麼是'm_arrColors'和'm_arrBoard'?碰撞發生時,「row」和「col」是什麼?很確定你只是出界了。 – tenfour 2011-12-19 08:07:47

+0

您是否檢查過「m_arrBoard [row] [col]'是否有效?你有沒有試過在調試器中運行它? – 2011-12-19 08:10:48

回答

1

顯而易見的原因是您正在訪問陣列的無效索引 - m_arrColorsm_arrBoard

例如,如果m_arrBoard的尺寸爲3x3,並且您嘗試訪問m_arrBoard[3][3],則會發生崩潰(可能是實際上未定義的行爲)。 - 請記住,C++數組是基於0的

用調試程序運行它,並檢查是否發生這種情況。