调用以下函数时出现无效指针错误。为什么会这样?
void Get(const char* value)
{
string st("testing string");
string val = st.substr(1, st.length());
value = val.c_str();
}
int main()
{
const char *val = NULL;
GetVal(val);
cout<<val;
}
目标是返回子串。
最佳答案
Get()
中的
val
变量在 Get()
返回后被销毁,因此指向 val
的指针 body 变得无效。另外 value
参数是原始指针的拷贝,所以 main()
函数中的原始 val
指针保持不变,仍然保持为 null指针值。
改成
string Get()
{
string st("testing string");
string val = st.substr(1, st.length());
return val;
}
关于C++ 字符串 : Invalid pointer error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4803352/