For some reason my program is crashing in the loop, and im unsure what is causing the problem
Here is my code.
#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();
}
Here is the input file i am using
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
needs to be
This is because arrays in C++ start at the index 0, so when you allocate an array of size three, as you do above with
board = new int*[boardsize];, the indices of this array will be0, 1, 2, ... boardsize-1, whereas your algorithm was using1, 2, 3, ... boardsizewhich will be an out of bounds access because you only have n blocks allocated and you are trying to access (modify, actually) block n + 1, which will result in a segmentation fault.