C ++ void指针 [英] C++ void pointer
问题描述
我使用HDF5库从c ++中的HDF5文件读取数据,我遇到的问题是以下:
I am using an HDF5 library to read data from an HDF5 file in c++ and the call I am having problems with is the following:
status = H5Dread(
hdf5_dataset,
hdf5_datatype,
hdf5_dataspace_in_memory,
hdf5_dataspace_in_file,
H5P_DEFAULT,
buf
);
最后一个参数应该是一个void指针,但是当我尝试传递向量g ++给我以下错误:
The last argument is supposed to be a void pointer, and I have a vector of floats that I want to be allocated, however when I try to pass the vector g++ gives me the following error:
错误:不能转换
'std :: vector< float,std :: allocator< float> >'到
'void *'
for'6'
到'herr_t H5Dread(hid_t,hid_t,hid_t,hid_t,hid_t,void *)'
有什么方法可以直接写入向量而不必分配内存两次?
Is there any way that I can write directly to the vector without having to allocate the memory twice?
推荐答案
As std :: vector
保证数据存储在连续的内存中,可以将向量转换为如下的指针:
As std::vector
guarantees the data is stored in contiguous memory, you can convert a vector to a pointer like so:
std::vector<float> myFloats;
void *ptr = static_cast<void*>(&myFloats[0]); // or &myFloats.front()
编辑:如果您正在写入, code> push_back ,请确保 resize
先有足够的空间!
if you are writing to it without calling push_back
, make sure you resize
enough space first!
这篇关于C ++ void指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!