Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D Matrix allocation on heap in c++

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 M can by dynamically determined.
  • Con: Indexing of M is a bit of a pain. (M[i * m + j])

Second approach

typedef int dim[2];
dim* M = new dim[n];
  • Pro: Indexing of M is 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.

like image 931
Woltan Avatar asked Oct 07 '11 08:10

Woltan


1 Answers

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;
}
like image 174
crazyjul Avatar answered Sep 28 '22 16:09

crazyjul