简体   繁体   中英

Problem understanding C++ string - why are we using strcpy here?

string str;
str="hi brother";
char * cstr = new char [str.length()+1];
strcpy (cstr, str.c_str());

why don't we just do this

char *cstr = str.c_str();

if I try to do this then it gives an error. I can't understand what's the meaning of const char and char

why do we use strcpy function here?

You can use constant char pointer instead (if you want a read-only version):

const char * cstr = str.c_str();

or copy it to a char[] using strcpy() if you want to modify the new string ( char[] ) later

You need to use strcpy there if you want cstr to end up pointing to a copy of the string, or really character array. If you want it to end up pointing to the same character array that str holds internally then you would use

const char* cstr = str.c_str();

it must be const because str owns that string so only it is allowed to modify it; this is what const means.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM