I'm currently doing some programming in C++ and I'm having a lot of trouble trying to declare and initialize a dynamic 2D array of type int. This is supposed to be an object oriented program but the only real experience I have in creating this kind of array is with everything in one file.
Here's my current attempt, this is the object's class data from my header file. (without the get/set methods, as those shouldn't be relevant to this issue.)
class SlidingPuzzle {
private:
int height;
int length;
int** theBoard = NULL;
public:
SlidingPuzzle();
SlidingPuzzle(int, int);
~SlidingPuzzle();
};
And this is the constructor 'SlidingPuzzle();' from my source file
SlidingPuzzle::SlidingPuzzle() {
this->height = 3;
this->length = 3;
this->theBoard = new(int*[this->height]);
for (int i = 0; i < this->height; i++) {
this->theBoard[i] = new(int[this->length]);
}
for (int i = 0; i < this->height; i++) {
for (int j = 0; j < this->length; i++) {
this->theBoard[i][j] = 0;
}
}
}
An exception is thrown at this->theBoard[i][j] = 0;
Am I anywhere close to something functional here? Or am I doing this completely the wrong way?
This is an essential part of the program I'm making, and I can't really keep going without resolving this.
Edit: error was a small typo in
for (int j = 0; j < this->length; i++) {
this->theBoard[i][j] = 0;
}
Accidentally put i instead of j, causing it to go out of bounds, thanks.