Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

standards

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++)
   {
       T[i*N+j]=...;
   }
like image 889
Calmarius Avatar asked Oct 24 '10 16:10

Calmarius


2 Answers

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) = ....

like image 76
casablanca Avatar answered Oct 12 '22 23:10

casablanca


Because multidimensional array is something different then array of arrays/pointers.

like image 42
Šimon Tóth Avatar answered Oct 12 '22 23:10

Šimon Tóth