C++ 字符串 : Invalid pointer error

标签 c++

调用以下函数时出现无效指针错误。为什么会这样?

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/

相关文章:

c++ - 在 opencv 中创建晕影过滤器?

python - Boost.Python 返回引用现有 c++ 对象的 python 对象

c++ - enable_shared_from_this 不适用于 xcode 5

c++ - Boost 序列化/反序列化存档 "stream error"异常

C++:如何专门针对左值和右值

c++ - c++中类型之间的转换

c++ - 关于智能指针的问题

C++ - 避免异常内存泄漏

c++错误使用模板继承baseClass

c++ - 定义双感叹号?