Declaring a pointer to multidimensional array and allocating the array

const int someheight = 3;
const int somewidth = 5;

int (*array)[somewidth] = new int[someheight][somewidth];

I just found this ancient answer still gets read, which is a shame since it's wrong. Look at the answer below with all the votes instead.


Read up on pointer syntax, you need an array of arrays. Which is the same thing as a pointer to a pointer.

int width = 5;
int height = 5;
int** arr = new int*[width];
for(int i = 0; i < width; ++i)
   arr[i] = new int[height];

I suggest using a far simpler method than an array of arrays:

#define WIDTH 3
#define HEIGHT 4

int* array = new int[WIDTH*HEIGHT];
int x=1, y=2, cell;
cell = array[x+WIDTH*y];

I think this is a better approach than an array of an array, as there is far less allocation. You could even write a helper macro:

#define INDEX(x,y) ((x)+(WIDTH*(y)))

int cell = array[INDEX(2,3)];

A ready to use example from here, after few seconds of googling with phrase "two dimensional dynamic array":

int **dynamicArray = 0;

// memory allocated for elements of rows. 
dynamicArray = new int *[ROWS];

// memory allocated for  elements of each column.  
for( int i = 0 ; i < ROWS ; i++ ) {
    dynamicArray[i] = new int[COLUMNS];
}

// free the allocated memory 
for( int i = 0 ; i < ROWS ; i++ ) {
    delete [] dynamicArray[i];
}
delete [] dynamicArray;