Array Serialization issues

07b9e9e8483468e4a0e1bac1843e6e74
0
Snoob 105 Oct 04, 2013 at 11:45

Actually I try to implement my first serialization mechanisms with c++. Anything is working fine with single values and strings, but when I try to serialize a simple array it fails:

int dataArray[] = { 11, 22, 33, 44, 5, 6, 7, 8, 9, 10 };
int size = 10;
  
// write data
std::vector<char> test; 
const char* ptr = reinterpret_cast<const char*>(&dataArray);
std::copy(ptr,ptr+size, std::back_inserter(test));

// read data
int resArray[10];
memcpy(&resArray, &test[0], sizeof(char)*size);
  
for(int i=0; i<size;i++){
  std::cout << "Get [" << i << "]: " << resArray[i] << std::endl;
}

Only the first 3 values are returned correctly if I try to store my datas as char or unsigned char. Thanks for any help.

4 Replies

Please log in or register to post a reply.

3bedfd8ea4ba99514bae60813fe211fc
0
mcosta 102 Oct 04, 2013 at 12:59

I think this is more appropriate as a question in StackOverflow.

Anyway, your problem is in:

std::copy(ptr,ptr+size, std::back_inserter(test));

You need to give the size of the data in bytes since you’re accessing the array via a char*:

std::copy(ptr,ptr+(size*sizeof(int)), std::back_inserter(test));

07b9e9e8483468e4a0e1bac1843e6e74
0
Snoob 105 Oct 04, 2013 at 14:07

Thanks for the hint with the size. But this was not the issue, the failure still exists using now:

 std::copy(ptr,ptr+(size*sizeof(int)), std::back_inserter(test));
3bedfd8ea4ba99514bae60813fe211fc
0
mcosta 102 Oct 04, 2013 at 14:13

The same applies to the following line:

memcpy(&resArray, &test[0], sizeof(char)*size);

to

memcpy(&resArray, &test[0], sizeof(int)*size);

07b9e9e8483468e4a0e1bac1843e6e74
0
Snoob 105 Oct 04, 2013 at 14:22

Damn! Thanks, stupid failure. I think I’ts time to make a break and take a nap ;o)