Multidimensional Array via new Operator

◀ Multi-dimensional Array via malloc()▶ Why Start at Index 0 instead of Index 1?
Amazon C++ provides new operator which is a better way to dynamically allocate memory than malloc(). You can use either one but new is recommended, in part due to its conciseness. Here is a demonstration of how to declare a two-dimensional array dynamically using new operator:
int **a2Darray;
a2Darray = new int*[3];
a2Darray[0] = new int[1];
a2Darray[1] = new int[2];
a2Darray[2] = new int[3];
a2Darray[0][0] = 1;
a2Darray[1][0] = 2;
a2Darray[1][1] = 3;
a2Darray[2][0] = 4;
a2Darray[2][1] = 5;
a2Darray[2][2] = 6;
As we can see, a2Darray is a two-dimensional array with a total of 6 elements. Each element can be accessed via [][] notation. By the same token, a three-dimensional array looks like:
int ***a;
a = new int**[3];
a[0] = new int*[1];
a[1]  =new int*[2];
a[2] = new int*[3];
a[0][0] = new int[2];
a[1][0] = new int[2];
a[1][1] = new int[2];
a[2][0] = new int[3];
a[2][1] = new int[3];
a[2][2] = new int[3];
a[0][0][0] = 0;
a[0][0][1] = 1;
a[1][0][0] = 2;
a[1][0][1] = 3;
…
To deallocate memory allocated by using new, use delete. Using delete on a pointer that did not use new is not allowed.

The syntax of new is similar to that of Java, one of the most popular high level programming languages. Therefore I recommend that you use new operator instead of malloc() to dynamically allocate memory!
◀ Multi-dimensional Array via malloc()▶ Why Start at Index 0 instead of Index 1?

fShare
Questions? Let me know!