how to set char * value from std string (c_str()) not working

后端 未结 5 482
孤街浪徒
孤街浪徒 2020-12-20 22:38

i dont know but this not working for me im getting garbege value when i try to set char * value from function that returns std string :

string foo()
{
  st         


        
相关标签:
5条回答
  • 2020-12-20 23:17

    How about:

    printf("%s", foo.c_str() );
    

    Or better still, forget about using character pointers.

    0 讨论(0)
  • 2020-12-20 23:33

    Pass a memory location to foo() and have foo modify that:

    void foo (string* _out_newStr)
    {
        _out_newStr->assign("dummy string"); //This is wrong -> _out_newStr = "dummy string";
        return;
    }
    

    Then when you are using the "c_str()" function of the string object you will return a const char* value, as already pointed out.

    0 讨论(0)
  • 2020-12-20 23:34

    The lifetime of the data pointed to by cc is the same as the lifetime of the string it came from (at best - if you modify the string it's even shorter).

    In your case, the return value of foo() is a temporary that is destroyed at the end of the initialization of cc.

    To avoid the compilation error in char *cc = foo().c_str() you shouldn't cast to char*, you should switch to const char *cc, since const char* is what c_str() returns. That still doesn't solve the main problem, though.

    The simplest fixes are:

    printf("%s", foo().c_str()); // if you don't need the value again later
    
    const string s = foo();
    const char *cc = s.c_str();  // if you really want the pointer - since it's
                                 // in the same scope as s, and s is const,
                                 // the data lives as long as cc's in scope.
    
    string s = foo();
    printf("%s", s.c_str());     // if you don't store the pointer,
                                 // you don't have to worry about it.
    
    std::cout << foo(); // printf isn't bringing much to this party anyway.
    
    0 讨论(0)
  • 2020-12-20 23:34

    The code-snippet invokes undefined behavior, because the temporary std::string created from the call is destroyed at the end of the expression but cc which is pointing to the destroyed object, is still used even after that.

    0 讨论(0)
  • 2020-12-20 23:37

    The result of foo is a temporary object that gets destroyed by the end of char * cc = ... line. Store it in constant reference:

    const string& cc = foo();
    printf ("%s", cc.c_str());
    
    0 讨论(0)
提交回复
热议问题