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:
First approach
int* M = new int[m * n];
- Pro: The size of
Mcan by dynamically determined. - Con: Indexing of
Mis a bit of a pain. (M[i * m + j])
Second approach
typedef int dim[2];
dim* M = new dim[n];
- Pro: Indexing of
Mis just how I want it to be. - Con: The size of the first dimension (m) cannot be set dynamically.
Question
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