[英]coping contents of the const char* type variable caused unexpected result
const char* mTest1; /*This variable has been assigned value before and
the print out indicates it is correct.*/
char* mTest2;
if(mTest1 != NULL){
mTest2 = new char[strlen(mTest1) +1]{};
std::copy(mTest1, mTest1 + strlen(mTest1), mTest2);
printf("\n===== mTest1 is: %s =============", mTest1);
printf("\n===== mTest2 is: %s =============", mTest2);
}
我希望这两个printf都应该打印出相同的结果。
但是,结果不正确。
===== mTest1 is: c52b =============
===== mTest2 is: c52bZZZZ@m�� =============
我在处理内容到mTest2时是否采取了任何错误的方法?
谢谢
我不是c++
,但是从这一行开始
std::copy(mTest1, mTest1 + strlen(mTest1), mTest2);
似乎您缺少在mTest2
复制空终止符的mTest2
。 也许你可以尝试
std::copy(mTest1, mTest1 + strlen(mTest1) + 1 , mTest2);
或者,您可以在复制字符串后使用
mTest2[strlen(mTest1)] = '\0';
复制后,您忘记在字符串的末尾添加终止符号'\\ 0':
const char* mTest1; /*This variable has been assigned value before and
the print out indicates it is correct.*/
char* mTest2;
if(mTest1 != NULL){
mTest2 = new char[strlen(mTest1) +1]{};
std::copy(mTest1, mTest1 + strlen(mTest1), mTest2);
mTest2[strlen(mTest1)] = '\0';
printf("\n===== mTest1 is: %s =============", mTest1);
printf("\n===== mTest2 is: %s =============", mTest2);
}
使用c样式的字符串(char *)时,始终应记住有关终止符号的信息。 与往常一样,复制运算符仅复制字符串的内容,而不复制符号的终止符,因为这是停止操作的信号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.