Contents Up << >>

How do I allocate multidimensional arrays using new?

There are many ways to do this, depending on how flexible you want the array sizing to be. On one extreme, if you know all the dimensions at compile-time, you can allocate multidimensional arrays statically (as in C):

  	class Fred { /*...*/ };

	void manipulateArray()
	{
	  Fred matrix[10][20];

	  //use matrix[i][j]...

	  //no need for explicit deallocation
	}
On the other extreme, if you want to allow the various slices of the matrix to have a different sizes, you can allocate everything off the freestore:

  	void manipulateArray(unsigned nrows, unsigned ncols[])
	//'nrows' is the number of rows in the array.
	//therefore valid row numbers are from 0 to nrows-1 inclusive.
	//'ncols[r]' is the number of columns in row 'r' ('r' in [0..nrows-1]).
	{
	  Fred** matrix = new Fred*[nrows];
	  for (unsigned r = 0; r < nrows; ++r)
	    matrix[r] = new Fred[ ncols[r] ];

	  //use matrix[i][j]...

	  //deletion is the opposite of allocation:
	  for (r = nrows; r > 0; --r)
	    delete [] matrix[r-1];
	  delete [] matrix;
	}