我有一个接受 void* buffer 参数的函数。这个函数(由 HDF here 提供。根据我的理解,它从数据集中读取信息到缓冲区中。我可以使用这个函数,但前提是我使用常量值创建 3d int 数组。我需要能够使用用户传入的值来执行此操作。 这是该函数的开始:
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);
}
这对我来说总是失败。但是,我之前在创建 data_out 数组时使用 const int 值的实现工作得很好:
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);
}
这很好用。根据我的理解,这个函数(我无法控制)需要相同维度的数据空间(例如,3D 数组只能与 3D 数组一起使用,而 2D 数组在将数据复制到缓冲区)。
所以,我的关键问题是我似乎无法弄清楚如何创建一个读取函数满意的 3D int 数组(函数参数是 void* 但我似乎无法得到任何东西除了 3d int 数组之外)。我尝试使用以下方法将 3D int 数组表示为数组数组的数组:
int*** data_out = new int**[NX];
但这也失败了。关于如何创建 int arrayName[非常量值][非常量值][非常量值]形式的 3D int 数组有什么想法吗?我知道您无法使用非常量值创建数组,但我添加它们是为了澄清我的目标。 C++ 中是否应该有一种方法可以使用函数参数作为实例化数组的值?
最佳答案
我认为最简单的方法是这样做:
int* data_out = new int[NX * NY * NZ];
然后您可以像这样访问此 1D 数组作为 3D 数组:
int value = array[z * NX * NY + y * NX + x];
在更 C++11 的风格中,您可以使用 std::vector
:
std::vector<int> data_out;
data_out.resize(NX * NY * NZ);
并像这样调用函数:
h5Dataset.read(data_out.begin(), H5::PredType::NATIVE_INT, memspace, h5Dataspace);
关于c++ - 使用传入参数在 C++ 中创建 3D 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41473853/