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

前端 未结 3 741
遥遥无期
遥遥无期 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:06

    It's because you return a pointer to a local variable, a local variable that goes out of scope when the function returns.

    You are already using std::string for the argument, use it instead of the array and the return pointer.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-14 18:27

    If your aim is to pass the content of a std::string to a function modifying the content of a char*:

    #include <iostream>
    #include <vector>
    
    void f(char* s) {
        s[0] = 'H';
    }
    
    std::vector<char> to_vector(const std::string& s) {
        return std::vector<char>(s.c_str(), s.c_str() + s.size() + 1);
    }
    
    int main(void)
    {
        std::string s = "_ello";
        std::vector<char> t = to_vector(s);
        f(t.data());
        std::cout <<  t.data() << std::endl;
    }
    
    0 讨论(0)
提交回复
热议问题