How do you dynamically allocate a 2D matrix in C++? I have tried based on what I already know:
#include
int main(){
int rows;
int c
Here is the most clear & intuitive way i know to allocate a dynamic 2d array in C++. Templated in this example covers all cases.
template T** matrixAllocate(int rows, int cols, T **M)
{
M = new T*[rows];
for (int i = 0; i < rows; i++){
M[i] = new T[cols];
}
return M;
}
...
int main()
{
...
int** M1 = matrixAllocate(rows, cols, M1);
double** M2 = matrixAllocate(rows, cols, M2);
...
}