0

I have wanted to return char*. But my code is like that:

something.str() --> it is returning string
 (in stringstream --> string str() const;)

I want to do that return char* as strstream does.

(strstream -->char* str();)

I am converting my codes to sstream and how can I do?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Fikri Uzun
  • 19
  • 3
  • 1
    you can call `c_str()` on `str()` to return a `char *` so `something.str().c_str()` should work as `str()` returns a [`std::basic_string`](http://en.cppreference.com/w/cpp/string/basic_string/c_str) – EdChum Oct 20 '17 at 12:27
  • 1
    I'm not sure, but I think printStream->str() is returning a string object with a copy (temporary) of the contents.then you are invoking c_str() on it and getting a const char *, and then casting away the const-ness, and then returning the pointer outside the function scope. I think since its a temporary value you are getting back from printStream->str(), you will be using a pointer to deallocated memory outside this function. – Fikri Uzun Oct 20 '17 at 12:30
  • Sorry what are you intending to do with the `char *`? Your question lacks context – EdChum Oct 20 '17 at 12:31
  • my other functions need char * returning.i dont want to fix them morely – Fikri Uzun Oct 20 '17 at 12:33
  • General answer: Analyze your situation, understand your problem, deploy the right tools. "Conversions" like this are almost never a matter of a simple search/replace. You need to figure out the right components and lifetimes and all that that make up the new idiom. – Kerrek SB Oct 20 '17 at 12:34
  • tried that but is it appropriate.i want to be sure. const_cast(printStream->str().c_str()); – Fikri Uzun Oct 20 '17 at 12:37
  • @FikriUzun again, `str()` returns a **TEMPORARY** string that is freed after the entire statement is finished, and you are not saving the string anywhere, so the retrieved `char*` is **USELESS** before you have a chance to even use it. You **MUST** save the string somewhere so it outlives your use of the `char*`, thus ensuring the `char*` remains pointing at valid memory. Otherwise, rethink your design. – Remy Lebeau Oct 20 '17 at 18:02

0 Answers0