简体   繁体   English

strcpy / strcat奇怪的字符输出

[英]strcpy/strcat strange character output

I have the following piece of code for a custom String class: 我有一个自定义String类的以下代码:

const String &String::operator+(const String &right)
{
   String temp;
   temp.length = length + right.length;
   temp.sPtr = new char [temp.length + 1];
   assert( sPtr != 0 );
   strcpy(temp.sPtr, sPtr);
   strcat(temp.sPtr, right.sPtr);
   return temp;
}

where sPtr is a char* . 其中sPtrchar*

But, when I execute this function on two strings, I get garbage characters as a result, like this: 但是,当我在两个字符串上执行此函数时,我得到了垃圾字符,如下所示:

 ]√Hâ«Ö“x˘" = "The date is" + " August 1, 1993

I don't have the slightest clue what is happening. 我没有丝毫的线索,发生了什么。 I've read a couple of testimonials of people who have gotten garbage characters before the resulting string is concatenated, but I don't understand at all why the entire string would be garbage characters. 我已经阅读了几个在结果字符串连接之前得到垃圾字符的人的推荐,但我完全不明白为什么整个字符串都是垃圾字符。

Any help would be really great. 任何帮助都会非常棒。 Thanks in advance! 提前致谢!

Don't return an object by reference that is 'temporary'. 不要通过“临时”引用返回对象。 Once the function ends the temp string is de-allocated, and since the string is set to temps address it becomes garbage. 函数结束后,临时字符串被解除分配,并且由于字符串被设置为临时地址,因此它变为垃圾。

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

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