Alex
Alex

Reputation: 141

How do I declare a two dimensional dynamic array inside of a Class in C++

I have a class that needs to have a two dimensional array that I can initialize during construction by passing it two parameters. How do you declare a two-dimensional dynamic array within a class.

class Life
{
public:
    Life (int rows, int cols);
    ~Life ();
    Life(const Life& orig);
    Life& operator=(const Life& rhs);

    void init();
    void print();
    void update();
    void instructions();
    bool user_says_yes();
private:
    int rows;
    int cols;

    int neighbor_count(int row, int col);
    int** grid;
};

Life::Life(int row, int col)
{
    rows = row;
    cols = col;
    grid = new [rows][cols];
}

I know there's something wrong with the array because in the constructor it says that it should be a constant value. But I will not know the value until the user enters the values. But somehow I need to have an array in this class that will be dynamically created to a specified size. For now I can not use vectors, but if you know how to make it work with vectors it might help others.

Upvotes: 0

Views: 740

Answers (2)

memo1288
memo1288

Reputation: 738

I do that like this:

grid=new int*[rows];
for(int i=0;i<rows;i++){
      grid[i]=new int[cols];
}

The first line initializes an array which will contain a total of rows pointers, and then each of these pointers is allocated to hold a total of cols integers. And in your destructor:

for(int i=0;i<rows;i++){
      delete[] grid[i];
}
delete[] grid;

Here you have to deallocate the rows first, because grid is storing their addresses, and deleting it first would cause you to lose them.

Keep in mind that if you copy an object of this class, you will need to do this initialization for the copy too. That includes the = operator and the copy constructor.

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308528

You're right, you should use a vector of vectors. But since you cannot...

There are two ways to do a two-dimensional vector. The first is to create a one-dimensional vector and condense the two dimensions into one when you access it. You can put that behind a class method if you want to treat it as 2-D. grid = new int[rows*cols]; grid[c*rows+r]

The second method is to make an array of pointers, where each pointer is a one-dimensional array for a row. You need to allocate all of the row pointers individually.

Upvotes: 0

Related Questions