How to cast vector to char*

前端 未结 4 983
粉色の甜心
粉色の甜心 2020-12-13 13:53

I have a buffer like this:

vector buf

How can I cast it to char*?

If I do:

(char *)buf
         


        
相关标签:
4条回答
  • 2020-12-13 14:25
    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());
    
    0 讨论(0)
  • 2020-12-13 14:39
    reinterpret_cast<char*>(buf.data());
    
    0 讨论(0)
  • 2020-12-13 14:45

    Try

    (char *)(&buf[0])
    

    or another, more C++ cast. But also tell us what you're using this for. It may be a bad idea.

    0 讨论(0)
  • 2020-12-13 14:46

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

    0 讨论(0)
提交回复
热议问题