c++ - Getting error with const char -


i trying implement functions below, output foo() bunch of nonsense. tried run debugger , didn't see problems inside append function. total variable in foo() isn't assigned value "abcdef". ideas why?

int main() {     cout<<"foo is"<<endl;     foo();     return 0; }  const char* append(const char* s1, const char* s2) {     string s(s1);     s += s2;     return s.c_str(); }  void foo() {     const char* total = append("abc", "def");     cout<<total; } 

because in append(), returned s.c_str(); then, s destructed, means pointer returned invalidated immediately.

let append() return std::string solve issue.

std::string append(const char* s1, const char* s2) {     return std::string(s1).append(s2); }  void foo() {     std::string total = append("abc", "def");     cout << total; } 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -