views:

50

answers:

4

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.

+1  A: 

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*).

ereOn
+3  A: 
std::string s(vec.begin(), vec.end());
// now use s.c_str()

I think this should be fairly safe.

maybe use the two-iterator constructor `s(vec.begin(), vec.end())` instead? Seems to be a bit more idiomatic.
Philipp
A: 

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.

Aamir
Only the constructor that doesn't take a size parameter requires the string to be null-terminated.
A: 

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
Philipp
Also, the memory can move around whenever more memory is reserved, so you'd have to make sure the vector isn't manipulated while the pointer exists.