Dynamically Creating Two-Dimensional Arrays in C++

C++ doesn’t take kindly to dynamic arrays. You can’t just plug a variable into some brackets and expect to make an array whatever size you want. There are technical reasons for this–compile time code v. run time code–but at the end of the day, it just isn’t happening.

However, it wouldn’t be a very useful language if there wasn’t some way to dynamically create arrays, so if you want to do it, you’re going to have to play with pointers. Doubly so (pun wholly and completely intended) for 2D arrays.

int size = 10;
int dyn_array1[size]; // this won't work :(

int *dyn_array2;
dyn_array2 = new int [size];  // but this will! now we effectively have an array with 10 slots

// as always, it is useful to think of 2d arrays as an array of arrays
int **dyn_array3; // note that we are pointing to a pointer. don't worry, i barely understand it myself
dyn_array3 = new int * [size]; // the dynamic array we just created is also a pointer, allowing us to stuff arrays in our arrays
for (int y = 0; y < size; y++) {
	dyn_array3[y] = new int [size]; // making each of our arrays into an array itself
// and now we have a 10x10 dynamically created array
// of course you can use any variable you want for size, and you can use a different variable for each dimension
delete [] dyn_array2; // deleting the original dynamic array
for (int i = 0; i < size; i++) { // delete it as you created it...
	delete [] dyn_array3[i]; // one at a time
delete [] dyn_array3; // and then the whole shebang

It looks simple, but discovering this nearly killed me. If only I could genuinely wrap my head around pointers… I would recommend that to anyone who wants to be a better programmer than I.

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>