Jeremy G
Jeremy G

Reputation: 2409

C++ HDF5 Use dimensions of dataset as const int

I would like to use the dimension of my HDF5 dataset to create an array. I'm using the following code to find the dimensions of my dataset.

#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <typeinfo>

#include "H5cpp.h"

using namespace H5;
int main() {
    std::string sFileName;
    sFileName = "test.h5";

    const H5std_string FILE_NAME(sFileName);
    const H5std_string DATASET_NAME("timestep:5.0");
    H5File file(FILE_NAME.c_str(), H5F_ACC_RDONLY);
    DataSet dataset = file.openDataSet(DATASET_NAME.c_str());

    DataSpace dataspace = dataset.getSpace();
    int rank = dataspace.getSimpleExtentNdims();

    // Get the dimension size of each dimension in the dataspace and display them.  
    hsize_t dims_out[2];
    int ndims = dataspace.getSimpleExtentDims(dims_out, NULL);
    std::cout << "rank " << rank << ", dimensions " <<
        (unsigned long)(dims_out[0]) << " x " <<
        (unsigned long)(dims_out[1]) << std::endl;

    const int xrows = static_cast<int>(dims_out[0]); //120
    const int yrows = static_cast<int>(dims_out[1]); //100

    std::cout << xrows * yrows << std::endl; //12000

    double myArr[xrows] // this also produces an error saying xrows is not a constant value
}

However, when I try to create an array using

double myArr[xrows*yrows];

I get an error saying that xrows and yrows are not constant values. How do I work around this?

Upvotes: 0

Views: 253

Answers (2)

Ripi2
Ripi2

Reputation: 7198

double array[c] only works if c is a constant value:

const int c = 10;
double array[c]; //an array of 10 doubles

When cis dynamic you use new:

int c = 5;
c *= 2; //c=10
double *array = new double(c);

Upvotes: 1

Kiryl Vusik
Kiryl Vusik

Reputation: 1

The size of such arrays must be a constant expression determined at compile time (e.g. see this link). In your case, you could use dynamic memory or STL-containers, such as std::vector.

Upvotes: 0

Related Questions