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

时间:2014-12-24 06:13:50

标签: c++ pointers

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时是否有任何错误的方法?

由于

2 个答案:

答案 0 :(得分:2)

我不是c++的常客,而是来自这一行

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

mTest2中复制空终结符似乎缺少了。也许你可以试试

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

或者,您可以在复制字符串后使用

手动添加
mTest2[strlen(mTest1)] = '\0';

答案 1 :(得分:1)

您忘记在复制后在字符串末尾添加终止符号'\ 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 *)时,你总是应该记住终止符号。像往常一样,复制操作符只复制字符串的内容,而不是终止符号,因为它是让它们停止的信号。

相关问题