## Posts tagged ‘Dynamic’

### Dynamic Memory Allocation for Two Dimensional Arrays in C++

In C++, a two-dimensional array can be declared simply like this

int a[10][20];

However, this declaration requires contanst array size and it is inconvenient when the array size vary. To avoid this issue, you can use dynamic two dimensional array. There are several ways to allocate a dynamic two-dimensional array in C++. In this post, I will show you three most frequent methods.

First one is flattening the two dimensional array into one dimensional array and using it as one dimensional array

//Allocate

int *a = new int[m*n];

//Use a[m][n]

for( int i = 0 ; i < m ; i++)

for ( int j = 0 ; j < n ; j++)

a[i*n + j] = 1;

//Deallocate

delete[] a;

Second method is using an array of dynamic one-dimensional arrays. It makes use of dynamic 2D array be easier. However, elements of array may not be continuous in memory

int **a = new int*[m];

for ( int i = 0 ; i < m ; i++)

a[i] = new int[n];

for ( int i = 0 ; i < m ; i++)

for ( int j = 0 ; j < n ; j++)

a[i][j] = 1;

for ( int i = 0 ; i < m ; i++) delete[] a[i];

delete[] a;

//Allocate

int **a = new int*[m];

int a[0] = new int[m*n];

for ( int i = 1 ; i < m ; i++) a[i] = a[i-1] + n;

//Use a[m][n]

for ( int i = 0 ; i < m ; i++)

for ( int j = 0 ; j < n ; j++)

a[i][j] = 1;

delete[] a[0];

delete[] a;