-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path29_dynamicMemoryAllocation2Darrays.cpp
49 lines (39 loc) · 1.32 KB
/
29_dynamicMemoryAllocation2Darrays.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
using namespace std;
int main(){
// While allocating the memory dynamically for 2 dimensional arrays, first we need to create a column of pointers which are basically the pointers with the base address of the rows and then we create corresponding columns using the row pointers and the array is created
int row,col;
cout<<"Enter the number of rows: ";
cin>>row;
cout<<"Enter the number of columns: ";
cin>>col;
// created the 2d array prototype using pointers
int** arr = new int*[row];
// now creating the corresponding columns for row pointers
for(int i=0; i<row; i++){
arr[i] = new int[col];
}
// taking the input elements to fill the array?
cout<<endl;
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
cout<<"arr["<<i<<"]["<<j<<"]: ";
cin>>arr[i][j];
}
}
// printing the whole 2d array /
cout<<endl;
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
// manually releasing the memory allocated for arrays
for(int i=0; i<row; i++){
delete[] arr[i];
}
delete[] arr;
cout<<endl<<"Memory released successfully...."<<endl;
return 0;
}