1 #include <cstdio>
2
3 // Returns a pointer to a newly created 2d array the array2D has size [height x width]
4
5 int** create2DArray(unsigned height, unsigned width)
6 {
7 int** array2D = 0;
8 array2D = new int*[height];
9
10 for (int h = 0; h < height; h++)
11 {
12 array2D[h] = new int[width];
13
14 for (int w = 0; w < width; w++)
15 {
16 // fill in some initial values
17 // (filling in zeros would be more logic, but this is just for the example)
18 array2D[h][w] = w + width * h;
19 }
20 }
21
22 return array2D;
23 }
24
25 int main()
26 {
27 printf("Creating a 2D array2D\n");
28 printf("\n");
29
30 int height = 15;
31 int width = 10;
32 int** my2DArray = create2DArray(height, width);
33 printf("Array sized [%i,%i] created.\n\n", height, width);
34
35 // print contents of the array2D
36 printf("Array contents: \n");
37
38 for (int h = 0; h < height; h++)
39 {
40 for (int w = 0; w < width; w++)
41 {
42 printf("%i,", my2DArray[h][w]);
43 }
44 printf("\n");
45 }
46
47 // important: clean up memory
48 printf("\n");
49 printf("Cleaning up memory...\n");
50 for (int h = 0; h < height; h++) // loop variable wasn't declared
51 {
52 delete [] my2DArray[h];
53 }
54 delete [] my2DArray;
55 my2DArray = 0;
56 printf("Ready.\n");
57
58 return 0;
59 }
60