Conceptual explanation of: double (*p)[3][4] = new double [2][3][4]

What does double (*p)[3][4] = new double [2][3][4] mean in english? How do I access individual elements of p?
Last edited on
I'll take a stab, but I have to say that I'm not 100% sure. I think it means that p is a pointer to the first element of a three-dimensional array (with elements of type double) of dimensions 2, 3, and 4.

You could access element (1, 2, 3) like this:

 
p[1][2][3] = 1;
Last edited on
So what does the (*p)[3][4] mean if it is a 3d array (2x3x4)?
Maybe its a 2 dimensional pointer array where the value at p[3][4] is initialized store an address pointing to a 3 dimensional array of (2x3x4)?

Thats the best I can come up with...
It allocates dynamic memory for two 2D arrays with size 3*4.
You shouldn't use multidimensional arrays at all, and you definitely shouldn't mix static and dynamic arrays, that's just bad.
Sorry- why shouldn't I use multidimensional arrays? There is really no way around it especially if you are dealing with VERY large data sets (my data set is not 3x4) it is 264x345- i am trying to do it all dynamically. How is this mixing static and dynamic? I have worked in other languages more adapt at handling large data sets, but I am only working out the logistics of this in C++. Please break down exactly what double (*p_[3][4] = new double [2][3][4] is doing. What do all of the characters mean? i.e. double allocate type of pointer p (what does [3][4] refer to?) to two dynamic 2d arrrays of size 3x4.
Last edited on
Sorry- why shouldn't I use multidimensional arrays? There is really no way around it especially if you are dealing with VERY large data sets

Yes, there is. Read this:
http://www.cplusplus.com/forum/articles/17108/
Unfortunately the suggestion to avoid MD arrays neglects pre-existing libraries for reading in files formatted a particular way (eg netcdf). Thanks anyways- I like the suggestion and in some cases it could be very useful- I will keep it in mind. Do you happen to know the breakdown of this syntax?
double (*p)[3][4]
The (*p) indicates that it's a pointer to an array, rather than an array of pointers. The array is of size [3][4] as idicated.

Therefore 'p' is a pointer to type double[3][4];

= new double[2][3][4];

This actually calls new [2] to create an array of double[3][4], the resulting pointer is assigned to 'p'.

The trick here is that arrays are their own type. This can be further clarified by typdefing these arrays:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
typedef double double34[3][4];

// now that it's typedef'd, this is a lot simpler:

double foo[3][4];
double34 bar;
  // 'foo' and 'bar' are exactly the same type

double (*p1)[3][4];
double34* p2;
  // 'p1' and 'p2' are exactly the same type

p1 = new double[2][3][4];
p2 = new double34[2];
  // above two lines are the same (only different is they assign to different pointers 
THANK YOU!
Topic archived. No new replies allowed.