C++ Dynamically Allocating Multidimensional Arrays
Sure, I knew how to do it with arrays.
I wasn’t sure how to do it with multi-dimensional arrays. See, like a chump I had always been declaring the array size as a const. never took the time to think about it.
Turns out it’s just doing a pointer to a pointer.
What a chump I am - sloppy coding throughout all my old code. It’s clean-up time.
// Example to create an array a[5][2] dynamically
int main(int argc, char* argv[])
{
int** a = new int*[5]; // Initialize the 1D Array
for (int i=0; i<5; i++) {
a[i] = 0; // Initialize all elements to zero.
a[i] = new int[2]; // Put 2 elements on each 1D element
for (int j=0; j<5; j++) {
a[i][j]=0; // Do it Again
}
}
delete[] a;
return 0;
}
There are four important things here
- Don’t forget to delete to free up the memory to use later on in the code. Otherwise it sits used until the program ends.
- If there isn’t enough memory to allocate it will throw an exception.
- You can’t delete until you initialize the array. Unhandled exception will greet you if you do.
- The compiler (.NET, v C++ 6 ,etc) will not be able to see the dimensions or contents of the array in a watch. You need to watch a specific element a[3][0] - Don’t get freaked out.