Why is my function returning garbage when it should return a char?

前端 未结 3 742
遥遥无期
遥遥无期 2021-01-14 17:55

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

3条回答
  •  一整个雨季
    2021-01-14 18:09

    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.

提交回复
热议问题