can I use strncpy or strcpy to do the same ? |
No.
Actually, strncpy (or strcpy) can not be used. It may be the same most of the time, but there are cases, were the result is different.
The thing is, that std::string may contain any byte sequence, including null-bytes in the middle. These will abort the copying when strcpy or strncpy is used but will be nicely copied along with memcpy.
Note, that c_str *always* adds an additional null byte, even if the string ends with 0 already. Hence, the memcpy-version is safe to use. You can also use the suggested way of copying size+1 bytes and just remove your 3rd line:
1 2
|
char *a=new char[s.size()+1]
memcpy(a,s.c_str(),s.size()+1);
|
Or you may use the string member function "data" with the explicit "setting to null" which is sometimes faster:
1 2 3
|
char *a=new char[s.size()+1]
a[s.size()]=0;
memcpy(a,s.data(),s.size());
|
(The reason it is sometimes faster is, that strings are allowed to share memory. Think of
string s = "abcd"; s2="abc";
. Here, s2 is allowed to point to the same memory as s, but if you call c_str() on s2, it will be copied to an own buffer to provide the required \0 termination. string::data() does not need this copying.)
Ciao, Imi.
Edit: Another note to any reader: Although std::string can have null-bytes in the middle, you should
NOT use this feature. It's unexpected and won't work with a lot of placed where you use std::string anyway. Usage of vector<char> is recommended for byte arrays instead.