I have a buffer like this:
vector buf
How can I cast it to char*?
If I do:
(char *)buf
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?
reinterpret_cast<char*>(buf.data());
reinterpret_cast<char*>(buf.data());
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.
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 &
.