如何投射向量< unsigned char>到char * [英] How to cast vector<unsigned char> to char*
问题描述
我有这样的缓冲区:
vector< unsigned char> buf
如何将其转换为char *?
如果我这样做:
(char *)buf
pre>
我得到这个错误:
/ home / richard /桌面/ richard / client / src / main.cc:102:错误:无效从类型'std :: vector< unsigned char,std :: allocator< unsigned char& >'to type'char *'
对于那些想知道为什么我试图这样做。我需要传递缓冲区到这个函数:
n_sent = sendto(sk,(char *)buf, ,0,(struct sockaddr *)& server,sizeof(server));
只接受char *。
解决方案
reinterpret_cast< char *> (& buf [0]);
向量保证其元素占用连续内存。所以你寻求的数据实际上是第一个元素的地址(注意
向量< bool>
,这个技巧将失败)。此外,为什么你的缓冲区向量< char>
不需要reinterpret_cast?
C ++ 11的更新
reinterpret_cast< char *>(buf.data());
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*.
解决方案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 buffervector<char>
so that you don't need to reinterpret_cast?Update for C++11
reinterpret_cast<char*>(buf.data());
这篇关于如何投射向量< unsigned char>到char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!