0

I am newbie in c++. In the following code, I call two methods, first initialize and then connect:

const char* str;

void initialize() {
    string temp = "blah blah";
    str= temp.c_str();
    cout << "str: " << str << endl; //prints: "str: blah blah"
    temp = "foo bar";
    cout << "str: " << str << endl; //prints: "str: foo bar"
}

I want to know why changing temp variable, causes str variable to change too and what is the best and safe way to set a value for const char*?

Thanks

user5439180
  • 117
  • 9
  • See http://www.cplusplus.com/reference/string/string/c_str/ – MrTux Nov 08 '15 at 12:46
  • [Question 6441218](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) is not a duplicate of this at all. Reopen. – Tom Zych Nov 08 '15 at 13:40

0 Answers0