Two alternatives for dynamic allocation of multidimensional arrays.
int main() {
typedef int Matrix10[10][10];
int **vec;
Matrix10 *vec2;
int i,j;
vec = new int*[10];
for (i = 0; i < 10; i++) {
vec[i] = new int[10];
for (j = 0; j < 10; j++)
vec[i][j] = 0;
}
vec2 = new Matrix10[1];
for (i = 0; i < 10; i++)
for (j = 0; j < 10; j++)
(*vec2)[i][j] = 0;
return 0;
}
/Per W
On Thu, 26 Feb 2004, Nicolas Rosner wrote:
> > How is a multidimensional array dynamically initialised? In other
> > words [...]
> > what is the correct syntax for initialising for example ar[10][10]
> > with new?
>
> That syntax will work with static variables, i.e.
>
> int arr[10][10];
>
> But it won't work at all with new. You will need to declare the array
> as if it were one-dimensional, i.e.
>
> int* arr = new int[num_rows * num_cols];
>
> and then do the math "by hand" when accessing elements, e.g.
>
> arr[x * num_cols + y] = foo;
>
> I can already hear you screaming "but that totally sucks! the language
> should provide a better way to do it!", but before you do so, please
> remember that arrays are and have always been very low-level in C and
> C++. If you want nicer syntax, all you have to do is write a Matrix
> class to encapsulate the array, or even better, get one of the several
> excellent ones that already exist out there.
>
> For a more thorough discussion of this issue, check out the C++ FAQ
> Lite:
>
> http://www.parashift.com/c++-faq-lite/freestore-mg
|