Trouble creating a dynamic 2d array as a private class member

So I'm creating a 2D array with variable rows and columns decided by the user.

I can create it by dynamically allocating it. However, this only works if I create it in my main function. If I attempt to create it as a private data member for my class, it gives errors.

Here is the working code I use in main - (just quickly jotted these codes down by memory)
1
2
3
4
5
  int **someArray = new int*[variableRows];
  for(int j = 0; j < variableColu; ++j)
    {
        someArray[l] = new int [variableColu];
    }


Here is what I want to do but it doesn't work due to the variable rows and columns

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//matrix.hpp file
class Matrix
{
   private: 
   int **someArray;
   int r;
   int c;

   public:
   Matrix (int r, int c);

}

//Matrix.cpp file

Matrix::Matrix(int r, int c)
{
  **someArray = new int*[r];
  for(int j = 0; j < c; ++j)
    {
        someArray[j] = new int [c];
    }
}



I receive these errors for the second code, which doesn't make sense to me since it works fine in main.

Matrix.cpp: In constructor ‘Matrix::Matrix(int, int)’:
Matrix.cpp:5:15: error: invalid conversion from ‘int**’ to ‘int’ [-fpermissive]
**someArray = new int*[r];

 
**someArray = new int*[r];

You're actually dereferencing someArray here. Remove both of the *s and it should work.
1
2
3
4
5
6
Matrix::Matrix( int rows, int cols ) : r(rows), c(cols)
{
    // **someArray = new int*[r] ;
    someArray = new int*[r] {} ;
    // ...
}


Consider using std::vector< std::vector<int> > as the representation of the matrix.
@integralfx

That seemed to work perfectly! Doesn't make sense to me why I had to change it within the class though.

@JLBorges

Will play around with that configuration and see if it's better for my program
Topic archived. No new replies allowed.