[英]C++ string: Invalid pointer error
I am getting an invalid pointer error when I call the below function. 当我调用下面的函数时,我收到一个无效的指针错误。 Why is this happening? 为什么会这样呢?
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;
}
The objective is to return the substring. 目的是返回子字符串。
val
variable inside Get()
gets destroyed once Get()
returns, thus the pointer to val
body becomes invalid. 一旦Get()
返回, Get()
val
变量将被销毁,因此指向val
主体的指针无效。 Also value
parameter is a copy of the original pointer, so the original val
pointer in main()
function is left unchanged and still holds a null pointer value. 另外, value
参数是原始指针的副本,因此main()
函数中的原始val
指针保持不变,并且仍保留空指针值。
Change it to 更改为
string Get()
{
string st("testing string");
string val = st.substr(1, st.length());
return val;
}
I see two mistakes: 我看到两个错误:
val.c_str()
to a pointer that is local to GetVal()
; 您分配一个val.c_str()
的指针是本地GetVal()
; val
is destroyed at the end of GetVal()
, so the pointer value would be invalid anyway. val
在GetVal()
的末尾销毁,因此指针值无论如何都是无效的。 Prefer using std::string
. 最好使用std::string
。
string Get()
{
string st("testing string");
return st.substr(0, st.length()/2);//returning substring
}
string s = Get();
By the way, an interesting article (by Herb Sutter) you would like to read now is: 顺便说一句,您现在想阅读的一篇有趣的文章(由Herb Sutter撰写)是:
GotW #88: A Candidate For the “Most Important const” GotW#88:“最重要的const”候选人
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.