Is there a way to convert the above?
If so what is the best way?
I guess you can loop through the vector and assign to a const char*
, but I'm not sure if that is the best way.
Is there a way to convert the above?
If so what is the best way?
I guess you can loop through the vector and assign to a const char*
, but I'm not sure if that is the best way.
Maybe you could use a std::string
instead of the std::vector<char>
?
I believe std::string
is similar to std::vector<char>
so you can use it the same way, and benefit of its additional functions.
If so, std::string
has a method .c_str()
that returns a null-terminated C-string (a const char*
).
std::string s(vec.begin(), vec.end());
// now use s.c_str()
I think this should be fairly safe.
You can do something like this:
std::string str(&myVec[0], myVec.size());
And then str.c_str()
will return you a const char *
to play with. But this is assuming that the data in the vector is null-terminated. If it is not, then there are no guarantees.
Try the simple
LPCSTR str = &vec[0];
A vector already contains the contiguous storage that C strings require. But be careful that vec
is already null-terminated, and that vec
cannot be destroyed while str
is still used. Generally vec
can be destroyed as soon as it is not used anymore, so storing pointers into vec
is dangerous and will lead to crashes. OTOH, passing the pointer as argument might be fine:
f(&vec[0]); // f takes a LPCSTR parameter