If you want to use a function that writes const char*
as a parameter, you can use the following method
std::string str = "I want to convert string to char*";;
const char * c = str.c_str();
In this case, it cannot be modified because it is const
.
To enable modification (for example, char*
, you can:
std::string str = "I want to convert string to char*";;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writeable[str.size()] = '\0'; // Don't forget to add a zero at the end of the string
delete[] writable;
However, this method can cause memory leaks, so it's better to use the bottom one. This is a standard way of not needing another library It manages the memory on its own
std::string str = "I want to convert string to char*";
std::vector<char> writable(str.begin(), str.end());
writable.push_back('\0');
char* ptr = &writable[0];
std::cout << ptr;
© 2024 OneMinuteCode. All rights reserved.