what is the best way to copy a string to a char*

I really mean copy, not point to. so i assume

string s = "test";
char* c = s.c_str();

will not do the work.

wondering what is the best way to do it.

Thanks
create dynamic char array char* c = new char[s.length()+1];
+1 for the \0
then copy the contents with memcpy(c, s.c_str(), s.length()+1)
thanks. in this case, will strcpy do the same work ? as

char* c = new char[s.length() + 1];
strcpy(c, (char*) s.c_str());

That looks right but what is with the cast?
char* c = strdup( s.c_str() ); // does malloc of strlen( s ) + 1 bytes for you
...
free( c ); // when done
thank you guys for the help.
the (char*) is unnecessary.
maybe will stay with strcpy, unless there is benefit on it. as I am trying not to mix free and delete in the same project. easy for me to mess up.

have a good day
None of the mentioned methods is "best", because of two reasons:
1) c_str() may actually reallocate a string, if there is no place for an additional character. This is redundant.
2) strcpy, strdup determine length of the string using O(n) algorithm. But we already know this length.

I suggest:

1
2
3
4
std::string s = "...";
char * c = new char [s.size()+1];
std::copy(s.begin(), s.end(), c);
c[s.size()] = '\0';
this is an interesting approach I overlooked. thanks
And perhaps for adorning and flexibility:

1
2
3
4
5
6
7
8
9
std::string s = "message";

std::ostringstream oss;
oss << "*** " << s << " ***";
oss << std::ends;

std::string const & buffer( oss.str() );
char * c = new char [ buffer.size() ];
std::copy( buffer.begin(), buffer.end(), c );

I've used this when overriding std::exception::what() in a multi-threaded application.
Topic archived. No new replies allowed.