faqts : Computers : Programming : Languages : C++

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

197 of 217 people (91%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

How can i declare a 2D dynamic array in C++, like a 1D int *x = new int[10];, but 2D. syntax?

Aug 27th, 2007 14:54
John Doe, dick weed, Jean-Michel Carriere,


int ** array = new int*[rows];
for(int i = 0; i < rows; i++)
   array[i] = new int[cols];
this code creates a dynamically allocated matrix of size rowsXcols.  
Analogous to the non-dynamically allocated array:
int array[rows][cols];
______________________________
Or you could just write the following code:
int **array = reinterpret_cast<int**>( new int[rows*cols] );
for( int k = 0; k < rows; k++ )
  array[k] = reinterpret_cast<int*>( array ) + k * cols;
... /* some code */
delete[] reinterpret_cast<int*>( array );