Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast vector<unsigned char> to char*

Tags:

c++

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*.

like image 923
Richard Knop Avatar asked Nov 23 '10 09:11

Richard Knop


People also ask

Can you cast unsigned char to 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.


1 Answers

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?

Update for C++11

reinterpret_cast<char*>(buf.data()); 
like image 112
Armen Tsirunyan Avatar answered Oct 08 '22 08:10

Armen Tsirunyan