How to cast vector to char*

前端 未结 4 991
粉色の甜心
粉色の甜心 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:46

    It's very unlikely that you want to cast vector to unsigned char *, but you can get a a valid pointer like this:

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

提交回复
热议问题