-2

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.

  • Possible duplicate of [How do I declare a 2d array in C++ using new?](https://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new) – MrTux Nov 10 '19 at 09:40
  • Whenever you think "dynamic array" you next thought should always be [`std::vector`](https://en.cppreference.com/w/cpp/container/vector). – Some programmer dude Nov 10 '19 at 09:41
  • By the way, `new` is an operator and not a function, you don't need parentheses around the type. – Some programmer dude Nov 10 '19 at 09:42
  • This approach may be worth considering: https://stackoverflow.com/questions/53038457/what-is-the-best-modern-c-approach-to-construct-and-manipulate-a-2d-array/53038618#53038618 – Galik Nov 10 '19 at 09:50

1 Answers1

0

This loop is wrong.

for (int j = 0; j < this->length; i++) {

You have to increment j, not i.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70