I am looking for a way to allocate a 2D (m x n) matrix on the heap where the elements are consecutive in memory. Currently I know of two ways to accomplish that:
int* M = new int[m * n];
M
can by dynamically determined.M
is a bit of a pain. (M[i * m + j]
)typedef int dim[2];
dim* M = new dim[n];
M
is just how I want it to be.Is there a way to allocate a 2D matrix dynamically on the heap where I can index the elements with [i][j]
and the memory allocation is consecutive?
I know it would make a lot of sense to use a class for that, but I am specifically looking for a way as described above.
You can try this
int** M = new int*[m];
int *M_data = new int[m*n];
for(int i=0; i< m; ++i)
{
M[i] = M_data + i * n;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With