Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

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

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()] = '';
    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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...