« Dynamic memory allocation for Multi-dimensional array

Dynamic memory allocation for 2-D array

Dynamically allocating 2-D arrays

1int m, n;
2cin >> m >> n;
3int **p = new int *[m];
4for (int i = 0; i < m; i++)
5{
6 p[i] = new int[n];
7 for (int j = 0; j < n; j++)
8 {
9 cin >> p[i][j];
10 }
11}

dynamic_2d_array.jpg

De-allocating 2-D arrays

1for (int i = 0; i < m; i++)
2 {
3 delete[] p[i];
4 }
5 delete[] p;
6}

Final code

1#include <iostream>
2#include <iomanip>
3#include <algorithm>
4#include <string>
5#include <cstring>
6#include <vector>
7#include <cmath>
8#include <map>
9#include <climits>
10// climits for INT_MIN
11#include <unordered_map>
12using namespace std;
13int main()
14{
15 int m, n;
16 cin >> m >> n;
17 int **p = new int *[m];
18 for (int i = 0; i < m; i++)
19 {
20 p[i] = new int[n];
21 for (int j = 0; j < n; j++)
22 {
23 cin >> p[i][j];
24 }
25 }
26
27 for (int i = 0; i < m; i++)
28 {
29 for (int j = 0; j < n; j++)
30 {
31 cout << p[i][j] << " ";
32 }
33 cout << endl;
34 }
35
36 for (int i = 0; i < m; i++)
37 {
38 delete[] p[i];
39 }
40 delete[] p;
41
42 return 0;
43}