Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep copy std::string::c_str() to char * [duplicate]

Tags:

c++

string

Currently I have a complex function that myself and our team are not wanting to refactor to utilize std::string and it takes a char* which is modified. How would I properly make a deep-copy of string::c_str() into a char*? I am not looking to modify the string's internally stored char*.

char *cstr = string.c_str();

fails because c_str() is const.

like image 994
Nick Betcher Avatar asked Oct 17 '25 13:10

Nick Betcher


1 Answers

You can do it like this:

const std::string::size_type size = string.size();
char *buffer = new char[size + 1];   //we need extra char for NUL
memcpy(buffer, string.c_str(), size + 1);
like image 111
Michał Walenciak Avatar answered Oct 19 '25 04:10

Michał Walenciak