Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
947 views
Welcome To Ask or Share your Answers For Others

1 Answer

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...