C++ Allocating Dynamic Multidimentional Arrays

Aim
To demonstrate dynamic array allocation in C++. Dynamic array allocation in C++ can take many forms. Regardless of whether you use malloc or new, you have to be carefull when freeing up memory using free or delete. In these examples we will allocate three dimentional 3D arrays as it give a better insight than two dimentional 2D arrays. The examples are given below.

int***p Dynamic using malloc
int***p Dynamic using new
int (*p)[10][10] Sem-Dynamic using new.

Now let us look at these in more detail below.

Dynamic Malloc
The first way to allocate an array is using malloc and a pointer to a pointer to a pointer. You have to free all the arrays at the end Malloc doesn't call constuctors and free doesn't call destructors.
 1. #include <stdlib.h>
 2. #include <stdio.h>
 3. 
 4. int main(){
 5. 
 6.     int*** p;
 7. 
 8.     int x    = 10;
 9.     int y    = 10;
10.     int z     = 10;
11. 
12.     int i, j;
13. 
14.     p = (int***)malloc(x*sizeof(int**));
15. 
16.     for(i=0; i < x; i++){
17.         p[i] = (int**)malloc(y*sizeof(int*));
18.         for(j=0; j < y; j++){
19.             p[i][j] = (int*)malloc(z*sizeof(int));
20.         }
21.     }
22. 
23.     p[0][2][3]=100;
24.     p[4][5][4]=101;
25.     printf("values %d\n", p[0][2][3]);
26.     
27.     for(i=0; i < x ; i++){
28.         for(i=0; i < y ; i++){
29.             free(p[i][j]);
30.         }
31.         free (p[i]);
32.     }
33.     free (p);
34. }
Hide line numbers

Dynamic New
Now let us look at dynamically allocating an array using the new operator. You have to delete all the arrays after you have finished.
 1. #include <stdlib.h>
 2. #include <stdio.h>
 3. 
 4. int main(){
 5. 
 6.     int x = 10;
 7.     int y = 10;
 8.     int z = 10;
 9. 
10.     int i, j;
11. 
12.     int ***p; 
13.     
14.     p =  new int**[x];
15. 
16.     for(i=0; i<x; i++){
17.         p[i] = new int*[y];
18.         for(j=0; j<x; j++){
19.             p[i][j] = new int[z];
20.         }
21.     }
22. 
23.     p[1][2][3]=100;
24.     p[4][5][6]=100;
25.     printf("values %d\n", p[1][2][3]);
26. 
27.     for(i=0; i<x; i++){
28.         for(j=0; j<x; j++){
29.             delete [] p[i][j];
30.         }
31.         delete  [] p[i] ;
32.     }
33.     delete [] p;
34. }
Hide line numbers

Semi-Dynamic with 'new'
Next let us have a look at semi-dynamically allocating an array using 'new'. It's semi dynamic because you can vary only one array length and the others are fixed. p is basicall a pointer to a multidimentional array of int.
 1. #include <stdlib.h>
 2. #include <stdio.h>
 3. 
 4. int main(){
 5. 
 6.     int x = 10;
 7.     const int y(10);
 8.     const int z(10);
 9. 
10.     int i, j;
11. 
12.     int (*p)[y][z] = new int[x][y][z];
13.     
14.     p[0][2][3]=100;
15.     p[4][5][4]=101;
16.     printf("values %d\n", p[0][2][3]);
17. 
18.     delete [] p    ;
19. }
Hide line numbers

No comments: