In C++ 98, is this a legitimate method to cast from a string to a char *?
char * n = (char *) someString.c_str(); (In my original wording, the function above was recommended by a senior programmer)
Namely, is it a better method than:
s2 = (char *)alloca(s0.size() + 1); memcpy(s2, s0.c_str(), s0.size() + 1); (courtesy of convert string to char*)
If so, why?
Use Case:
I need to use a char*, but I don't need to alter the data after it is in the char*. I'm passing it to a display library.
I'm just looking for a short and sweet answer. Thanks!
Edit: I changed the wording to this question because it got down voted. I hope my rewording makes it a better question. I think the answers were interesting and insightful.
For the record: Anyone interested in this question, should look at all the responses. I could only pick one, but I found them all interesting.
mallocin C++ isn't great either. Just use&someString[0]in C++11 and ensure the null terminator isn't touched by whatever needs thechar *.c_strreturns a pointer to a constant string, i.e. a string you shouldn't modify, that's what thecstands for. The same goes for the method mentioned by Chris in his comment above, it's gives you a pointer to a constant string.std::stringuse a null-terminated buffer internally, and thatc_str()returns a pointer to that. Ref . So chris's method is safe so long as the null terminator is not overwritten.