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.
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.