I want to write multiple 2D char arrays into one HDF5 dataset. In the code below, there are two arrays in a struct and I put(std::copy) "hello"s to one array(name) and "hi"s to the other(nicknams). I thought that the result would look:
(b'hello', b'hey')
(b'hello', b'hey')
(b'hello', b'hey')
(b'hello', b'hey')
But when I actually run the code, the result looks like:
(b'hello', b'hey')
(b'(\xae\nVD\xae\nV\xff\xff', b'\xdc\x82\nV\x12\xd2\xfcv\x8f\x01')
(b'\x04', b'\x01')
(b'$\xf8O', b'9\x08\xd2\xd5\xb4\xf8O')]
Since the very first row looks fine, I guess that there’s something wrong with null characters when writing arrays to the dataset. I have looked into example codes on the official web page(https://support.hdfgroup.org/HDF5/examples/), but I still don’t understand where this problem come from. I’d like to know what the problem is and how to fix it.
#include "pch.h"
#include <iostream>
#include "H5Cpp.h"
using namespace H5;
const H5std_string MEMBER1("name");
const H5std_string MEMBER2("nickname");
struct newStruct1 {
char name[4][10]{};
char nickname[4][10]{};
};
void struct_to_dataset(newStruct1 *ptr_struct)
{
H5File file("file.h5", H5F_ACC_TRUNC);
hid_t dtype_str = H5Tcopy(H5T_C_S1);
size_t size = 10 * sizeof(char);
H5Tset_size(dtype_str, size);
hsize_t dim[] = { 4 };
DataSpace space(1, dim);
CompType mtype1(sizeof(newStruct1));
mtype1.insertMember(MEMBER1, HOFFSET(newStruct1, name), dtype_str);
mtype1.insertMember(MEMBER2, HOFFSET(newStruct1, nickname), dtype_str);
DataSet dataset = file.createDataSet("dset", mtype1, space);
dataset.write(ptr_struct, mtype1);
}
int main()
{
newStruct1 struct01;
newStruct1 *ptr01 = &struct01;
char word1[10] = { "hello" };
char word2[10] = { "hey" };
for (int i = 0; i < 4; i++) {
std::copy(word1, word1 + 10, ptr01->name[i]);
std::copy(word2, word2 + 10, ptr01->nickname[i]);
}
struct_to_dataset(ptr01);
}