Converting a char*
to a std::string
:
char* c = "Hello, world";
std::string s(c);
Converting a std::string
to a char*
:
std::string s = "Hello, world";
char* c = new char[s.length() + 1];
strcpy(c, s.c_str());
// and then later on, when you are done with the `char*`:
delete[] c;
I prefer to use a std::vector<char>
instead of an actual char*
; then you don't have to manage your own memory:
std::string s = "Hello, world";
std::vector<char> v(s.begin(), s.end());
v.push_back(''); // Make sure we are null-terminated
char* c = &v[0];
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…