How to cast vector to char*

前端 未结 4 989
粉色の甜心
粉色の甜心 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 (&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 , this trick will fail with it). Also, why isn't your buffer vector so that you don't need to reinterpret_cast?

    Update for C++11

    reinterpret_cast(buf.data());
    

提交回复
热议问题