为什么我的程序崩溃了
Why is my programming crashing
由于某种原因,我的程序在循环中崩溃,我不确定问题的原因
这是我的密码。
#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,这将导致分段错误。
相关文章:
- 提升 ASIO Async_receive崩溃程序
- 类指针方法崩溃程序
- get_body来自 IHTMLDocument2 崩溃程序
- 是否有可能存在不会崩溃程序的内存问题
- 调试运行时出现奇怪的崩溃程序(Eclipse C++)
- 儿童对话框 - setWindowTexta或sendmessagea崩溃程序-MFC
- 顶点阵列GLFW崩溃C 程序
- 将值分配给Float数据类型崩溃程序
- OpenCV-将变量添加到类成员崩溃程序
- boost::interprocess::managed_shared_memory 崩溃程序
- 将枚举值分配给整数崩溃程序
- SDL 1.2 -> SDL 2.0(崩溃程序)
- 空析构函数崩溃程序:C++
- 冒泡排序崩溃程序c++
- Ofstream关闭崩溃程序
- 删除字符* 崩溃程序
- c++矢量擦除崩溃程序
- Lua_getglobal崩溃程序
- 通过Copy Constructor创建的e2打印崩溃程序
- RNG崩溃c++程序