Why can't a multidimensional array be allocated with one new call in C++?

In C++ you can easily allocate one dimensional array like this:

T *array=new T[N];

And you can delete it with one statement too:

delete[] array;

The compiler will know the magic how to deallocate the correct number of bytes.

But why can't you alloc 2-dimensional arrays like this?

T *array=new T[N,M];

Or even like this?

T *array=new T[N,M,L];

If you want a multidimensional you have to do it like this:

T **array=new T*[N];
for(int i=0;i<N;i++) array[i]=new T[M];

If you want a fast program that uses matrices (matrix operations, eigenvalue algorithms, etc...) you might want to utilize the cache too for top performance and this requires the data to be in the same place. Using vector<vector<T> > is the same situation. In C you can use variable length arrays on the stack, but you can't allocate them on the heap (and stack space is quite limited), you can do variable length arrays in C++ too, but they won't be present in C++0x.

The only workaround is quite hackish and error-phrone:

T *array=new T[N*M];
for(int i=0;i<N;i++)
   for(int j=0;j<M;j++)


Your workaround of doing T *array=new T[N*M]; is the closest you can get to a true multi-dimensional array. Notice that to locate the elements in this array, you need the value of M (I believe your example is wrong, it should be T[i*M+j]) which is known only at run-time.

When you allocate a 2D array at compile-time, say array[5][10], the value 10 is a constant, so the compiler simply generates code to compute i*10+j. But if you did new T[N,M], the expression i*M+j depends on the value of M at the time the array was allocated. The compiler would need some way to store the value of M along with the actual array itself, and things are only going to get messy from here. I guess this is why they decided not to include such a feature in the language.

As for your workaround, you can always make it less "hackish" by writing a wrapper class that overloads operator (), so that you could do something like array(i, j) = ....

Need Your Help

Regular expression for extracting tag attributes

html regex

I'm trying to extract the attributes of a anchor tag (&lt;a&gt;). So far I have this expression:

WPF TextBox Validation

wpf validation textbox wpf-controls

I have validation hooked up to a model that is bound to the TextBox container. When the window is first opened validation errors appear as the model is empty, I do not want to see validation errors

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.