Const Char * test()返回String.c_Str()不能正常工作

时间:2012-08-02 12:27:44

标签: char const

我对此问题感到困惑:

Const Char* Test() {
    String a = "anything";
    Return a.c_str();
}

Void Main() {
    Cout << Test(); // returns crap!
}

有人知道我没想到的是什么吗? 此页面未经iPhone优化; - )

3 个答案:

答案 0 :(得分:1)

String a位于自动内存中,当您从Test()返回时会被销毁,因此分配给c_str的内存也会被释放

答案 1 :(得分:1)

尝试在堆上分配字符串:

string *a=new string("anything");
return (*a).c_str();

答案 2 :(得分:1)

C语言是基于堆栈的。 字符串a in函数Test()在堆栈中分配。

const Char* Test() {
   std::string a = "anything";  // Allocated in stack based
   return a.c_str(); // A is freeing for return.
}

Void Main() {
    std::cout << Test(); // returns crap!
}

const char* Test(std::string *a) {
   *a = "anything";
   return a->c_str();
}

Void Main() {
    std::string a;
    std::cout << Test(&a);
}

OR

const Char* Test() {
   **static** std::string a = "anything";  // Allocated in data memory
   return a.c_str(); // data memory freed when application terminating.
}

Void Main() {
    std::cout << Test();
}