Wednesday, October 2, 2019

How to Dynamically allocate memory to 2D array in c++?

There are multiple ways to allocate memory to 2D array dynamically. I will discuss few of theme here.

1) By creating the pointer of pointers of specific data types:
#include<iostream>
void free2DArrayMemory(int **, int);
using namespace std;
int main()
{
int row=3, col=4;
int **arr = new int*[row];
       //int **arr = (int **)malloc(sizeof(int)*row); //For C style memory allocation

for(int i=0; i<row; i++)
{
       arr[i] = new int[col];
               //arr[i] = (int*) malloc(sizeof(int)*col); // For C style
         }

int count = 10;
for(int r=0;r<row;r++)
for(int c=0;c<col;c++)
arr[r][c] = count++;

for(int r=0;r<row;r++)
{ for(int c=0;c<col;c++)
{
cout<<arr[r][c]<<" ";
//cout<<*(*(arr+r)+c)<<" ";
}
cout<<endl;
}

      free2DArrayMemory(arr,col);
return 1;
}

void free2DArrayMemory(int **arr, int col)
{
if(!arr)
return;

for(int i;i<col;i++)
{
delete []arr[i];
//free(arr[i]); //For C Stype
}
delete []arr;
//free(arr); //For C
}
-----------------------------------------------------------------------------------------

2) By creating the array of pointers:
#include<iostream>
using namespace std;
int main()
{
int row=3, col=4;
int *arr[row];

for(int i=0;i<row;i++)
arr[i] = new int[col];

int count = 10;
for(int r=0;r<row;r++)
for(int c=0;c<col;c++)
arr[r][c] = count++;

for(int r=0;r<row;r++)
{ for(int c=0;c<col;c++)
{
//cout<<arr[r][c]<<" ";
cout<<*(*(arr+r)+c)<<" ";
}
cout<<endl;
}
      free2DArrayMemory(arr,col);
return 1;
}

-----------------------------------------------------------------------------------------

3)