# new for 2D array

• 12-05-2006
Ene Dene
new for 2D array
Lets say that I want a dynamic 2D array, I would do it in following way:

Code:

`double (*koordinates)[3] = new double [number_of_points][3]`
where number_of_points variable is inputed while program runs, and [3] is number of dimensions od space. But what I don't know how to do is, how do I make a [3] also dynamic, for example, if I want to choose a number of dimensions while program is running.
I tried:
Code:

```double (*koordinates)[dimension]= new double [number_of_points][dimension] or double (*koordinates)(*dimension)= new double [number_of_points][dimension]```
and it doesn't work.
• 12-05-2006
Daved
Even better in C++:
Code:

`std::vector<std::vector<double> > koordinates(dimension, std::vector<double>(dimension));`
• 12-05-2006
SlyMaelstrom
Code:

```int **arry; size_t ARRY_X = 3; size_t ARRY_Y = 4;     arry = new int*[ARRY_X]; for(int i = 0; i < ARRY_X; i++)   arry[i] = new int[ARRY_Y];```
Quote:

Originally Posted by Daved
Even better in C++:

Agreed, but it's worth it to know how to allocate multi-dimensional arrays.
• 12-05-2006
Daved
I would leave your response there anyway since it actually answers the original question.
• 12-05-2006
Ene Dene
Thank you both.
• 12-05-2006
Mario F.
On a side note...

Do you really want to make the spacial dimension dynamic? Because if you are only working with 2 and 3 dimensions (generally that is the case), I would advise against it. You are complicating your life as far as deallocation is concerned. Count how many deletes you have to write.

In fact, when working with multiple dimension dynamic arrays, the best option is to move to one dimensional arrays. Read http://www.parashift.com/c++-faq-lit...html#faq-16.16, taking into consideration that a multidimensional array is in fact an array of arrays, as Sly demonstrated.

However, better yet is to not make the spacial dimensions dynamic. Use typedefs to simplify your array usage. Like this:

Code:

```typedef double koord_2D[2]; typedef double koord_3D[3]; koord_3D* Planet = new koord_3D[4]; koord_2D* Point = new koord_2D[4];```
You have now two types that map to 2D and 3D spacial objects. Planets is an array of 4 planets on a 3D coordinates system. Points is an array of 4 points on a Cartesian coordinate system.

Any function can then use the typedef as a parameter and all will be much clearer.

EDIT: Oh! and the deletes... you just need two. One for Planet and one for Point
• 12-05-2006
CornedBee