Re: how to I recast pointer to n-dim array in C++?
Housing wrote:
Hi all,
I have a pointer which is double * ptr,
it actually points to a 3D array.
For the sake of programming ease, is there a way to recast the double *
ptr into a form that I can access as follows:
ptr[m][n][k]
or
ptr[m, m, k]
???
Thanks a lot! I am looking for a good simple recast that does not lead to
processing overhead, i.e. probably a class-level wrap is too much
burden...
The following has undefined behavior, it may work on your platform.
#include <algorithm>
#include <iostream>
#include <iterator>
unsigned int const dim1 = 2;
unsigned int const dim2 = 3;
unsigned int const dim3 = 4;
unsigned int const size = dim1 * dim2 * dim3;
typedef float array1d [dim3];
typedef array1d array2d [dim2];
typedef array2d array3d [dim3];
typedef float * float_ptr;
int main ( void ) {
float_ptr fp = new float [ size ];
array3d & ar = reinterpret_cast< array3d& >( *fp );
for ( unsigned int i = 0; i < dim1; ++i ) {
for ( unsigned int j = 0; j < dim2; ++j ) {
for ( unsigned int k = 0; k < dim3; ++k ) {
ar[i][j][k] = i + j + k;
}
}
}
std::copy( fp, fp +size,
std::ostream_iterator< float >( std::cout, " " ) );
std::cout << '\n';
}
If you need something that avoids undefined behavior, a wrapper class would
probably be the way to go. I don't know of any casting magic that achieves
your objective without UB.
Best
Kai-Uwe Bux