CPP
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
//created by Vlad Apet
#include <iostream>
using namespace std;
int main() {
// Unlike a two dimensional fixed array, which can easily be declared like this:
// char b[100][100];
//Dynamically allocating a two-dimensional array is a little more challenging. You may be tempted to try something like this:
//char** b = new int[100][100];
// But it won't work.
// Unfortunately, this relatively simple solution doesn’t work if the rightmost array dimension isn’t a compile-time constant. In that case, we have to get a little more complicated. First, we allocate an array of pointers (as per below). Then we iterate through the array of pointers and allocate a dynamic array for each array element. Our dynamic two-dimensional array is a dynamic one-dimensional array of dynamic one-dimensional arrays!
char **b = new char*[100]; // allocate an array of 100 char pointers — these are our rows
for(int i = 0; i < 100; i++){
*b = new char[100];
} // these are our columns
// Deallocating a dynamically allocated two-dimensional array using this method requires a loop as well:
for(int i = 0; i < 100; i++){
delete[] b[i];
Enter to Rename, Shift+Enter to Preview
OUTPUT
Run