How to set char * value from std string (c_str ()) doesn't work

I don't know, but this does not work for me, getting the garbege value when I try to set the char * value from a function that returns std string:

string foo()
{
  string tmp ="dummy value";
  return tmp;
}

char* cc = (char *) foo().c_str(); // if i remove the casting im getting error 
// when i print the cc i get garbage 
printf("%s",cc);
+5
source share
5 answers

The lifetime of the data pointed ccto coincides with the lifetime of the line from which it came (at best, if you change the line that is even shorter).

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

char *cc = foo().c_str(), char*, const char *cc, const char* - , c_str(). .

:

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 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.
+13

foo - , char * cc = .... :

const string& cc = foo();
printf ("%s", cc.c_str());
+9

foo() foo:

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

, c_str() , const char *, .

+1

undefined, std::string, , , cc, , - .

0
source

What about:

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

Or better yet, forget about using character pointers.

0
source

All Articles