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

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

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

    #include 
    #include 
    
    void f(char* s) {
        s[0] = 'H';
    }
    
    std::vector to_vector(const std::string& s) {
        return std::vector(s.c_str(), s.c_str() + s.size() + 1);
    }
    
    int main(void)
    {
        std::string s = "_ello";
        std::vector t = to_vector(s);
        f(t.data());
        std::cout <<  t.data() << std::endl;
    }
    

提交回复
热议问题