I\'m a newbie in C++ learning the language and playing around. I wrote a piece of code which behavior I don\'t understand. Could someone explain why the code below prints ou
Your function is returning garbage because you're returning the address of a local variable which goes out of scope after your function returns. It should probably look like this:
char* str2char(const std::string &str)
{
char *const cset = new char[str.size() + 1]; // +1 for the null character
strcpy(cset, str.c_str());
return cset;
}
You will need to delete your variable r
by doing delete[] r;
. Ideally though you wouldn't be using raw pointers, and you would use std::string
for everything, or wrap the char *
in a std::unique_ptr
.