I'm trying to convert a std::string
to a char*
(copying rather than casting) due to having to pass some data to a rather dated API.
On the face of it, there are a number of ways to do this, but it was suggested that I do this as a vector which seemed sensible. However, when I tried this the result was garbled. The code is like:
const string rawStr("My dog has no nose.");
vector<char> str(rawStr.begin(), rawStr.end());
cout << "\"" << (char*)(&str) << "\"" << endl;
(Note the unpleasant C cast - using static_cast does not work which is probably telling me something)
When I run this I get:
"P/"
Clearly not right. I took a look at the vector in gdb
(gdb) print str
$1 = std::vector of length 19, capacity 19 = {77 'M', 121 'y', 32 ' ', 100 'd', 111 'o',
103 'g', 32 ' ', 104 'h', 97 'a', 115 's', 32 ' ', 110 'n', 111 'o', 32 ' ', 110 'n',
111 'o', 115 's', 101 'e', 46 '.'}
Which looks correct although there's no null terminator at the end, which is concerning. The size of the vector (sizeof(str)
) is 24 which suggests the characters are being stored as 8-bits.
Where am I going wrong?