简体   繁体   中英

c++: convert vector<char> to double

I am using vector<char> to send and receive data via socket. In this vector I stored data of different types. Unsigned Integer and Doubles. To decode the data from vector I am using copy function.

vector<char> myVector = ... smth;
double value = 0.0;
copy(myVector.begin(), myVector.begin() + sizeof(value), &value);

It works with Integer without problem. But...

My problem is, that the compile gives out an error "free(): invalid pointer: 0x00000000006d0e30" . I checked, the problem is with the double value, not with the vector. I looked the address of double value it was ( 0x6d0e38 ). Why the program tries to access the pointer backwards? I would be glad, if you can say me, what I am doing wrong. And is it the good way to decode message?

Thank you a lot.

I guess that you need to cast the pointer accordingly to make ptr++ use the right size ( sizeof(char) , opposed to sizeof(double) ):

vector<char> myVector = ... smth;
double value = 0.0;
std::copy(myVector.begin(), myVector.begin() + sizeof(value),
    reinterpret_cast<char*>(&value));

Don't do this. Send the string representation of the value through the socket.

std::stringstream ss;
double value = 0.0;
ss << value;

Then use ss.str() or if you really need a vector of char:

std::vector<char> v(ss.begin(), ss.end());

-- edit --
If you really need to keep data binary, do

  std::vector<char> v(sizeof(double));
  double val = 0.5;
  std::memcpy(&v[0],(char*)&val,sizeof(val));
  ...
  double* out = (double*)&v[0];
  std::cout << *out << std::endl;

It works with Integer without problem. But...

It most certainly will not work for integers. At least not for integers where sizeof(int) > 1 ! Because it will not write to just one integer, but spread the bytes in myVector over sizeof(T) integers, thus overwriting random memory. (see nightcracker's answer)

Please just use memcpy for this kind of copying:

vector<char> myVector = ... smth;
double value = 0.0;
assert(myVector.size() == sizeof(double));
memcpy(&value, &myVector[0], std::min(myVector.size(), sizeof(double)));
// as an alternative to the assert + std::min() above, you could also throw
// an exception if myVector.size() == sizeof(double) does not hold.
// (that's what I'd do if the size should always match exactly)

memcpy is made exactly for that kind of thing (copying raw memory), and I see no reason to use anything else here. Using std::copy does not make it better C++, especially when you're not doing it correctly. std::copy is for copying objects, not raw memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM