string to char[] conversion

Can someone explain how this works

1
2
3
4
//std::string s
char *a=new char[s.size()+1]
a[s.size()]=0;
memcpy(a,s.c_str(),s.size());


An explanation of how each line works would be helpful.
What are my alternative options - can I use strncpy or strcpy to do the same ?


Thanks....
Last edited on
1
2
3
char *a=new char[s.size()+1]
a[s.size()]=0;
memcpy(a,s.c_str(),s.size());
Allocates a char array with the size of the string plus one character for the null terminator
Sets the last character as null terminator
copies from the string


The last character thing is not required since c_str is already null terminated

can I use strncpy or strcpy to do the same ?
Yes
Last edited on
can I use strncpy or strcpy to do the same ?
Yes, as Bazzy said, and in this case you don't have to write a[s.size()]=0;. str(n)cpy does it for you.

EDIT:
The last character thing is not required since c_str is already null terminated
I think it is required coz he uses memcpy with s.size(); It wouldn't be required if he used memcpy with s.size();+1
Last edited on
So were I to use strncpy....

std::string s
char *a = new char[s.size()+1];
strncpy(a, s.c_str(), s.size());

is that correct ?


Thanks....


So were I to use strncpy....

1
2
3
std::string s
char *a = new char[s.size()+1];
strncpy(a, s.c_str(), s.size());


is that correct ?


Thanks....
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.
Last edited on
Topic archived. No new replies allowed.