Why can't you allocate a 2D array like this?

This is a discussion on Why can't you allocate a 2D array like this? within the C++ Programming forums, part of the General Programming Boards category; I've seen how to dynamically allocate a two-dimensional array row by row. But why couldn't you just simply allocate the ...

1. Why can't you allocate a 2D array like this?

I've seen how to dynamically allocate a two-dimensional array row by row. But why couldn't you just simply allocate the memory and cast it into a 2D array, like this:

Code:
```// I want a dynamically allocated int[2][2], so allocate enough memory:
int* buffer = new int [2 * 2];

// And do the cast:
int (*p_array) [2] [2] = (int (*) [2] [2]) buffer;

// ...

delete [] buffer;
// Or, delete [] p_array; ?```
I guess it's not technically an array of an array, but the result will achieve that effect. Also, this would be handy:

Code:
`int (&the_array) [2] [2] = *p_array;`

2. It's just not how the syntax for the language is.

3. Why not just use a vector<vector<int> > instead, or some other class that acts like a matrix?

4. I know there are better alternatives, but the code I used compiles, and it seems the memory gets deleted properly, too. I don't understand what's so bad about it (other than you can't delete individual rows).

5. You can combine a 2d array into a single allocation, there's nothing wrong with it. I know Bubba has posted examples here before, you may get some tips if you can find them in a search.

6. I find this a much easier solution than allocating row by row. A helper function could do most of the work:

Code:
```template <typename T, size_t x, size_t y>
int (*Allocate2DArray ()) [x] [y]
{
return new T [x * y];
}```

7. Just use Boost's multi_array class, which does the allocation (as a single block), and provides easy accessors, and lets you choose row-major or column-major, and supports even more dimensions.

8. Code:
`int (*array)[2] = new int[2][2];`
Should be what you want, if you really want an array with two subscripts.