我是 C++ 的新手,正在学习这门语言并四处游玩。我写了一段我不明白其行为的代码。有人可以解释为什么下面的代码打印出随机垃圾而不是列表中第一个字符串的第一个字符(即 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;
}
当我期望它输出 a
时,为什么我返回的是垃圾?
感谢任何帮助!
附言此代码的输出是随机的。它并不总是打印相同的字符..:S
最佳答案
这是因为你返回了一个指向局部变量的指针,一个在函数返回时超出作用域的局部变量。
您已经在使用 std::string
对于参数,使用它代替数组和返回指针。
关于c++ - 为什么我的函数在应该返回 char 时返回垃圾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21181233/