【发布时间】:2015-05-21 19:26:14
【问题描述】:
我想将 STL 容器中包含的数据写入 HDF5 文件。根据我收集的信息,我需要声明一个连续的内存块并使用"hdf5.h" C API 将数据从内存缓冲区传输到磁盘。
对于常规数据空间,过程很简单;只需使用new 在堆栈上创建临时数组。 HDF5“理解”这样的内存布局。
当处理不规则数据空间时,情况就不同了,因为必须使用专用类型 hvl_t。
以下 sn-p 有效,但不是 ISO C++(11):
// Test data
std::vector< std::vector<int> > jagged_array(3);
jagged_array[0] = {0};
jagged_array[1] = {0, 1, 2, 3};
jagged_array[2] = {0, 1, 2};
hvl_t X[jagged_array.size()];
for (unsigned int i = 0; i < jagged_array.size(); ++i) {
X[i].len = jagged_array[i].size();
int * ptr = (int *) malloc (X[i].len * sizeof(int));
for (unsigned int j = 0; j < X[i].len; ++j) {
ptr[j] = jagged_array[i][j];
}
X[i].p = (void *) ptr;
}
我的 C非常生锈了;除了非法行 hvl_t X[jagged_array.size()]; 之外,这个 sn-p 几乎完全是从 HDF5 示例页面中删除的。
我应该如何声明一个hvl_t,其大小在运行时确定?
它肯定涉及malloc,但我真的很难过。
【问题讨论】:
-
你试过
hvl_t * X = (hvl_t *)malloc(jagged_array.size() * sizeof(hvl_t));吗? -
感谢@Lashane 的快速回答。我刚试过,它会产生错误
error: invalid conversion from ‘void*’ to ‘hvl_t*’ -
感谢您发布错误,我已将演员表添加到示例中
-
是的,你可以阅读任何关于 c 的书,不要使用 c++ 书籍,通常这部分称为动态数组
-
@JGab:如果您的编译器抱怨从
void *到hvl_t *的转换,它不是 C 编译器。 C 编译器会自动执行此操作; C++ 编译器没有。
标签: c memory memory-management malloc hdf5