简体   繁体   English

应对const char *类型变量的内容导致意外结果

[英]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);    
}

I would expect both of these two printf should print out the same result. 我希望这两个printf都应该打印出相同的结果。

However, the result is not correct. 但是,结果不正确。

===== mTest1 is: c52b =============
===== mTest2 is: c52bZZZZ@m�� =============

Is there any wrong approach I've taken in coping the contents to mTest2? 我在处理内容到mTest2时是否采取了任何错误的方法?

Thanks 谢谢

I am no expeert in c++ , but from this line 我不是c++ ,但是从这一行开始

std::copy(mTest1, mTest1 + strlen(mTest1), mTest2);

It looks like you're missing to copy the null terminator in mTest2 . 似乎您缺少在mTest2复制空终止符的mTest2 Maybe you can try 也许你可以尝试

 std::copy(mTest1, mTest1 + strlen(mTest1) + 1 , mTest2);

Or, you can add that manually, after copying the string, using 或者,您可以在复制字符串后使用

mTest2[strlen(mTest1)] = '\0';

You forgot to add teminating symbol '\\0' at the end of the string after copying it: 复制后,您忘记在字符串的末尾添加终止符号'\\ 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);    
}

When you work with c-style strings (char *), you always should remember about terminating symbols. 使用c样式的字符串(char *)时,始终应记住有关终止符号的信息。 As usual, copying operators copy only content of the string, and not terminating symbol, because it's signal for them to stop. 与往常一样,复制运算符仅复制字符串的内容,而不复制符号的终止符,因为这是停止操作的信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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