2012-02-20 106 views
-4

由於某種原因,我的程序在循環中崩潰,並且我不確定是什麼導致了問題爲什麼我的編程崩潰

這是我的代碼。

#include<iostream> 
#include<string> 
#include<fstream> 
using namespace std; 



int main() 
{ 
    ifstream fin; 
    ofstream fout; 

    fin.open("dice.in"); 
    fout.open("dice.out"); 

    string line; 
    int boardsize; 
    int top; 
    int side; 

    fin >> boardsize >> top >> side; 
    while(boardsize != 0) 
    { 
     int ** board; 
     board = new int*[boardsize]; 

     //creates a multi dimensional dynamic array 
     for(int i = 0; i < boardsize; i++) 
     { 
      board[i] = new int[boardsize]; 
     } 

     //loop through the 2d array 
     for(int i = 0; i <= boardsize; i++) 
     { 
      getline(fin, line); 
      for(int j = 0; j < boardsize; j++) 
      { 
       if(i != 0) 
       board[i][j] = (int)line[j]; 
      } 
      line.clear(); 
     } 


     fin >> boardsize >> top >> side; 
    } 

    fin.close(); 
    fout.close(); 
} 

這裏是我使用

3 6 4 
632 
562 
463 
3 6 4 
632 
556 
423 
7 6 4 
4156*64 
624*112 
23632** 
4555621 
6*42313 
4231*4* 
6154562 
0 0 0 
+3

您是否使用了打印跟蹤或分步調試器來查找崩潰的行?這應該是相當微不足道的,並且會大大增加你真正看到這個的機會。 – 2012-02-20 18:15:40

+0

你有沒有想過使用調試器來找出原因? – 2012-02-20 18:15:53

回答

2
//loop through the 2d array 
    for(int i = 0; i <= boardsize; i++) 
    { 
     getline(fin, line); 
     for(int j = 0; j < boardsize; j++) 
     { 
      if(i != 0) 
      board[i][j] = (int)line[j]; 
     } 
     line.clear(); 
    } 

需求是

//loop through the 2d array 
    for(int i = 0; i < boardsize; i++)   // note < instead of <= 
    { 
     getline(fin, line); 
     for(int j = 0; j < boardsize; j++) 
     {          // not I deleted if statement 
      board[i][j] = (int)line[j]; 
     } 
     line.clear(); 
    } 

這是因爲在C++中數組的索引0處開始輸入文件,所以當你分配一個大小爲3的數組,如上面用board = new int*[boardsize];所做的那樣,這個數組的索引將是0, 1, 2, ... boardsize-1,其中因爲你的算法使用1, 2, 3, ... boardsize這將是一個超出界限的訪問,因爲你只有n塊被分配,並且你試圖訪問(修改,實際上)塊n + 1,這將導致分段錯誤。