#include <memory>
using namespace std;
void newMem(string str, char **cp) {
size_t size = str.size();
*cp = new char[size + 1];
memcpy(*cp, str.c_str(), size + 1);
}
int main()
{
string str = "hello";
char *out = nullptr;
newMem(str, &out);
cout << out << endl;
int i = 0;
while(out[i] != '\0') {
printf("%c, ", out[i]);
++i;
}
delete [] out; //开辟了char数组,释放时也应该是数组释放,可以使用valgrind检测出来:valgrind --tool=memcheck ./main
return 0;
}
void copyStringOut(const std::string& src, char** dest)
{
try {
*dest = new char[src.size() + 1]; // +1 for NUL
src.copy(*dest, src.size());
(*dest)[src.size()] = '\0';
} catch(const std::exception&) {
*dest = NULL;
throw;
}
}