所以在c ++中,正常的cstyle字符串可以像这样启动:
char cString[] = "my string";
如何使用动态内存做同样的事情?
为什么这不起作用?
char *charPtr;
charPtr = new char("make this the value of the c string");
感谢您的帮助
答案 0 :(得分:0)
你不能像这样初始化一个c风格的字符串。 首先,你需要一个指向字符串开头的指针。然后需要分配足够的内存来保存该字符串,即字符数+终止'\ 0'。对于strlen和strcpy,您应该包含cstring标头。最后,您需要将字符串复制到内存块。
char *str; //pointer to string
str = new char[strlen("The string to copy")+1]; //allocate memory
//strlen returns the number of charaters of a string exluding the '\0', so we need to add 1
//either use a string constant, or another cstyle string, or input the length manually
strcopy(str, "The string to copy");//strcpy copies the content of the string constant to str
//be sure to set the last element of the string to '\0'
str[strlen(str)] = 0; // or '\0'
//if str has 5 char it returns 4 because the last is \0
//but the array goes from 0 to 4, so 4 is the last element
并且不要忘记使用delete [] str;如果你摆脱了字符串!