I am trying to binary serialize the data of vector. In this sample below I serialize to a string, and then deserialize back to a vector, but do not get the same data I started with. Why is this the case?
vector<size_t> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
string s((char*)(&v[0]), 3 * sizeof(size_t));
vector<size_t> w(3);
strncpy((char*)(&w[0]), s.c_str(), 3 * sizeof(size_t));
for (size_t i = 0; i < w.size(); ++i) {
cout << w[i] << endl;
}
I expect to get the output
1
2
3
but instead get the output
1
0
0
(on gcc-4.5.1)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…