Some answers here say a 2-dimensional array is an array of pointers to other arrays. That's not true (where to store pointers, if all you allocate is the data of the array!?). Instead, a 2-dimensional array is an array of other arrays. Thus, you will have to change the type of your member:
FooBar::FooBar()
: _array( new int[10][10] )
{ }
int (*_array)[10];
That is because new[]
returns a pointer to the first element of an array created. This element is an array of 10 integers, and thus the member type change. If the syntax scares you off, simplify it with a temlate (this template is equivalent to boost::identity
).
template<typename T> struct identity { typedef T type; };
FooBar::FooBar()
: _array( new int[10][10] )
{ }
identity<int[10]>::type *_array;
This effectively works like a in-place typedef. Of course, like with any use of new[]
, it needs a proper delete[]
placed in the destructor and invoked when your object is destroyed.
Since new[]
allocates an array of elements that have types known at compile time, you can only have the first (most outer) dimension set to a runtime value - all others must have values known at compile time. If that is not what you want, you will have to allocate an array of pointers, like some other answers say.
But notice, to avoid further confusion, that those are not multi-dimensional arrays. They are single-dimensional arrays of pointers, which happen to point at other single-dimensional arrays.