Why is my function returning garbage when it shoul

2019-02-18 22:41发布

问题:

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 out random junk and not the first character of the first string in the list (that is a).

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
#include <climits>
#include <stdio.h>


char* str2char(std::string str)
{
    char cset[str.size()+1]; // +1 for the null character
    for(int i = 0; i < str.size(); i++)
    {
        cset[i] = str[i];
    }
    cset[str.size()] = '\0';
    return cset;
}

int main (int argc, char * const argv[]) {



    std::vector< std::string > ladontakadet;
    ladontakadet.push_back("aabcbbca");
    ladontakadet.push_back("abcdabcd");
    ladontakadet.push_back("cbbdcdaa");
    ladontakadet.push_back("aadcbdca");
    ladontakadet.push_back("cccbaaab");
    ladontakadet.push_back("dabccbaa");
    ladontakadet.push_back("ccbdcbad");
    ladontakadet.push_back("bdcbccad");
    ladontakadet.push_back("ddcadccb");
    ladontakadet.push_back("baccddaa");

    std::string v = ladontakadet.at(0);
    char *r;
    r = str2char(v);
    std::cout << r[0] << std::endl;
    return 0;
}

Why is my returning garbage, when I'm expecting it to output a?

Thnx for any help!

P.S. The output of this code is random. It doesn't always print the same character..:S

回答1:

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;
}


回答2:

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.



回答3:

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.