为什么我的编程崩溃
问题描述:
由于某种原因,我的程序在循环中崩溃,并且我不确定是什么导致了问题为什么我的编程崩溃
这是我的代码。
#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
答
//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,这将导致分段错误。
您是否使用了打印跟踪或分步调试器来查找崩溃的行?这应该是相当微不足道的,并且会大大增加你真正看到这个的机会。 – 2012-02-20 18:15:40
你有没有想过使用调试器来找出原因? – 2012-02-20 18:15:53