【发布时间】:2014-11-04 06:02:23
【问题描述】:
我被要求在以下代码中查找错误 这段代码只是打印 abcdef,对我来说似乎没什么害处,但会感谢任何建议
#include <iostream>
using namespace std;
const char* append(const char* s1, const char* s2) {
string s(s1);
s += s2;
return s.c_str();
}
void foo() {
const char* total = append("abc", "def");
cout<<"total = "<<total<<endl;
}
int main() {
foo();
return 0;
}
【问题讨论】:
-
提示:当
append返回时,s将不复存在。 -
当 s 超出范围时,它将删除指针,因此从 append 函数返回的将包含垃圾字符。
-
谢谢大家,这解决了我的困惑
-
代码缺少
#include <string>所以不会编译......
标签: c++