I have a buffer like this:
vector<unsigned char> buf
How can I cast it to char*?
If I do:
(char *)buf
I get this error:
/home/richard/Desktop/richard/client/src/main.cc:102: error: invalid cast from type ‘std::vector<unsigned char, std::allocator<unsigned char> >’ to type ‘char*’
For those wondering why I am trying to do this. I need to pass the buffer to this function:
n_sent = sendto(sk,(char *)buf,(int)size,0,(struct sockaddr*) &server,sizeof(server));
And it only accepts char*.
You can pass a pointer to a different kind of char , but you may need to explicitly cast it. The pointers are guaranteed to be the same size and the same values.
reinterpret_cast<char*> (&buf[0]);
The vector guarantees that its elements occupy contiguous memory. So the "data" you seek is actually the address of the first element (beware of vector <bool>
, this trick will fail with it). Also, why isn't your buffer vector<char>
so that you don't need to reinterpret_cast?
reinterpret_cast<char*>(buf.data());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With