Generating 2D array

Ok, Still have issues with pointers.

I want to be able to dynamically allocate for a 2d array. I was wondering what was necessary, this was my first attempt:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
namespace Matrix{
template <class T> T * GenerateMatrix (int rows, int columns)throw(std::string){
    if (rows>15||columns>15) {
        throw std::string ("Too many rows or columns in Generate Matrix");
    }
    T** array = new T*[rows];
    for(int i=0; i<columns;++i){
        array[i] = new T[columns];
    }
    for (int i=0;i<rows;i++){
        for (int j=0;j<columns;j++){
            array[i][j]=0;
        }
    }
    return &&array;
}
int main (){
    double * array = Matrix::GenerateMatrix<double>(3,5);
}

Now I think the problem is the array is deallocated once GenerateMatrix is out of scope. The error when I try to compile is:
|18|error: invalid conversion from 'void*' to 'double*'|
So if you could point me in the right direction as how to generate a 2d array dynamically I would appreciate it.

I guess I could try:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Matrix {
    int *rows, *columns;
  public:
    Matrix (int,int);
    ~Matrix ();
    double** ary = new double*[rows];
    for(int i = 0; i < rows; ++i){
        ary[i] = new double[colums];
    }
    };

Matrix::Matrix (int a, int b) {
  rows = new int;
  columns = new int;
  *rows = a;
  *columns = b;
}

Matrix::~Matrix () {
  delete rows;
  delete columns;
}

but man, that gives the most error messages I've ever seen

Last edited on
due to your unfavorable format of braces you simply forgot one + some mistakes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace Matrix{
template <class T> T ** GenerateMatrix (int rows, int columns)throw(std::string){ // NOTE: T**
    if (rows>15||columns>15) {
        throw std::string ("Too many rows or columns in Generate Matrix");
    }
    T** array = new T*[rows];
    for(int i=0; i<columns;++i){
        array[i] = new T[columns];
    }
    for (int i=0;i<rows;i++){
        for (int j=0;j<columns;j++){
            array[i][j]=0;
        }
    }
    return array; // NOTE: no &&
} // NOTE
}
int main (){
    double ** array = Matrix::GenerateMatrix<double>(3,5); // NOTE: **
}
Also note the idea of passing back an allocated pointer is a bad idea -- as it makes memory leaks much more likely and makes the code much harder to use.

I'd go with your new idea of putting it in a class and have the appropriate deleting in the dtor. Although in your Matrix class, there's no reason to allocate 'rows' and 'columns' dynamically like that.
Topic archived. No new replies allowed.