Contents Up << >>

Does C++ have arrays whose length can be specified at run-time?

Yes, in the sense that STL has a vector template that provides this behavior. See on "STL" in the "Libraries" section.

No, in the sense that built-in array types need to have their length specified at compile time.

Yes, in the sense that even built-in array types can specify the first index bounds at run-time. E.g., comparing with the previous FAQ, if you only need the first array dimension to vary, then you can just ask new for an array of arrays (rather than an array of pointers to arrays):

  	const unsigned ncols = 100;
	//'ncols' is not a run-time variable (number of columns in the array)

	class Fred { ... };

	void manipulateArray(unsigned nrows)
	//'nrows' is a run-time variable (number of rows in the array)
	{
	  Fred (*matrix)[ncols] = new Fred[nrows][ncols];

	  //use matrix[i][j]

	  //deletion is the opposite of allocation:
	  delete [] matrix;
	}
You can't do this if you need anything other than the first dimension of the array to change at run-time.