Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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*.
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?
Update for C++11
reinterpret_cast<char*>(buf.data());
–
–
–
–
It's very unlikely that you want to cast vector<unsigned char>
to unsigned char *
, but you can get a a valid pointer like this:
vector<unsigned char> v;
unsigned char *p = &*v.begin();
That strange expression will give you the pointer to the start of the internal allocated array created by the vector. If you modify the vector at all it may no longer be valid.
The reason for the redundant looking &*
is that the *
is really operator *
on the iterator returned by v.begin()
. That returns a reference to the first char of the array which you can then take the address of with &
.
–
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.