Creating a 3D array in C++ using passed in parameters

103 views Asked by At

I have a function that takes in a void* buffer parameter. This function (which is provided by HDF here. From my understanding, it reads info from a dataset into the buffer. I have this working, but only if I create a 3d int array using constant values. I need to be able to do this using values passed in by the user. Here is the start of that function:

void* getDataTest(int countX, int countY)
{
    int NX = countX;
    int NY = countY;
    int NZ = 1;

    int data_out[NX][NY][NZ]; //I know this doesn't work, just posting it for reference

   //.
   //. more code here...
   //.

   // Read function is eventually called...
   h5Dataset.read(data_out, H5::PredType::NATIVE_INT, memspace, h5Dataspace);
}

This constantly fails on me. However, my previoud implementation that used const int values when creating the data_out array worked fine:

void* getDataTest(int countX, int countY)
{
    const int NX = 5;
    const int NY = 5;
    const int NZ = 1;

    int data_out[NX][NY][NZ]; 

   //.
   //. more code here...
   //.

   // Read function is eventually called...
   h5Dataset.read(data_out, H5::PredType::NATIVE_INT, memspace, h5Dataspace);
}

This works fine. From my understanding, this function (which I have no control over) requires dataspaces of the same dimensionality (e.g. a 3D array will only work with a 3D array while a 2D array will only work with a 2D array when copying over the data to the buffer).

So, my key problem here is that I can't seem to figure out how to create a 3D int array that the read function is happy with (the function parameter is a void* but I can't seem to get anything other than a 3d int array to work). I've tried a 3D int array represented as an array of arrays of arrays using:

   int*** data_out = new int**[NX];

but this failed as well. Any ideas on how I can create a 3D int array of the form int arrayName[non-constant value][non-constant value][non-constant value]? I know you can't create an array using non-constant values, but I added them in an attempt to clarify my goal. Should there be a way in C++ to use function parameters as values for instantiating an array?

2

There are 2 answers

2
Creak On BEST ANSWER

I think the easiest is to do this:

int* data_out = new int[NX * NY * NZ];

You can then access this 1D array as a 3D array like that:

int value = array[z * NX * NY + y * NX + x];

In a more C++11 style, you can use an std::vector:

std::vector<int> data_out;
data_out.resize(NX * NY * NZ);

And calling the function like that:

h5Dataset.read(data_out.begin(), H5::PredType::NATIVE_INT, memspace, h5Dataspace);
0
Malcolm McLean On

Do it like this:

    std::vector<int> array;

    array.resize(Nx*Ny*Nz);

    array[z*Ny*Nx + y*Nx + x] = value

It's nice to have the array[z][y][x] syntax, but supporting it is more trouble than it is worth.