Re: Passing multidimensional arrays to functions
In article <1149462948.782297.78680@u72g2000cwu.googlegroups.com>,
<sherwood@programmer.net> wrote:
A multi-dimensional array A is to be allocated at runtime and passed to
a function. I am struggling with two cases:
1) All but the first dimension of A are known at compile time. For
example, the array is complex<double> A[N][6][6]. I can allocate the
storage using 'new', but
complex<double> *A = new complex<double> [N*6*6];
doesn't work, because now the type of A does not match my function
prototype, complex<double> A[][6][6].
2) Other dimensions of A are unknown at compile time. For example,
complex<double> A[N1][2][N3]. Here my function prototype contains
complex<double> *A, and within the function I do the subscript offset
calculation i*s2+j*s3+k. I am passing s2 (2 in this example) and s3 (N3
here) to the function. I allocate using
complex<double> *A = new complex<double> [N1*2*N3];
and the compiler accepts this. However, it would be preferable to be
able to address array elements within the called function as
A[i][j][k], rather than as A[i*s2+j*s3+k].
Can someone suggest a straightforward way to deal with these two cases,
preferably one that doesn't involve installing a new class library?
google TNT [a numeric template library of 1,2,3 dim arrays] Its a
simple template library with only headers and everything it uses in
namespace TNT. To use A[i][j] notation directly you need a T** and
T** array2 // an array of T * each points to the start of a row of
array2.
to do A[i][j][k] directly you need a T*** each entry is a T** whose
entries are the rignt subscript. Its easier to use TNT::Array2D<T> or
TNT::Array3D<T> and if your called code takes T** or T**, and
dimensions
just pass them from the TNT::Array2D/3D to the functions.
TNT::Array2/3D<T> is a reference counted class providing little more
than normal subscript access and conversions to C notation operator
T**() or operator T***().
If you don't use TNT itself the logic of the operator []'s s and data
arrangement. Essentially a T * to contain the actual data and T **
to point to the rows, a T*** to point to the 2d layers...
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]