0
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));

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

0
102 Oct 04, 2013 at 12:59

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

 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)); 

0
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));

0
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); 

0
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)