64 Multidimensional Arrays in C++
Today's topic is multi-dimensional arrays. It is essential to understand 31 Arrays in C++ and 16 POINTERS in C++ because pointers are crucial when dealing with any type of array (since arrays are memory blocks, and the straightforward way to handle memory is by using pointers).
1. Differences Between Multi-dimensional Arrays and Regular Arrays
Starting with a two-dimensional array as an example, it is essentially an array of arrays (a three-dimensional array would be an array of arrays of arrays, and so on), which is a collection of arrays.
One strategy we consider when dealing with arrays is using pointers. We have a pointer that points to the beginning of the array in memory. Imagine having an array of pointers; eventually, you get a memory block containing contiguous pointers, each pointing to some array in memory. Thus, what you get is a collection of pointers to arrays, which is an array of arrays.
#include <iostream>
int main()
{
int* array = new int[50];
int** a2d = new int*[50]; // Here we allocate a buffer of pointer objects
std::cin.get();
}
Three-dimensional array (just for understanding):
int*** a3d = new int**[50];
for (int i = 0; i < 50; i++)
{
a3d[i] = new int*[50];
for (int j = 0; j < 50; j++)
a3d[i][j] = new int[50]; // Two levels of dereferencing
// int** ptr = a3d[i];
// ptr[j] = new int[50];
}
a3d[0][0][0] = 0;
Back to the two-dimensional array:
int** a2d = new int*[50]; // Here we allocate a buffer of pointer objects
for (int i = 0; i < 50; i++)
a2d[i] = new int[50];
a2d[0][0] = 0;
a2d[0][1] = 0;
a2d[0][2] = 0;
Since this is heap allocated, we need delete[]
to free the memory. However, be aware that delete[] a2d
only deletes the array of pointers that store the actual integer arrays. If you delete it, you will cause a memory leak of the 200 bytes of memory space that stores the actual 50 arrays because we can no longer access them. Therefore, we need:
2. Cache Misses
int** a2d = new int*[5]; // Create a 5x5 two-dimensional array
for (int i = 0; i < 5; i++)
a2d[i] = new int[5];
Can you think of a better way to store 25 integers?
You can store them in a one-dimensional array: