为什么我的函数返回的垃圾,当它应该返回一个char?

编程入门 行业动态 更新时间:2024-10-15 04:21:43
本文介绍了为什么我的函数返回的垃圾,当它应该返回一个char?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是C ++的新手学习语言并玩耍。我写了一段代码,我不明白的行为。有人可以解释为什么下面的代码打印出随机垃圾,而不是列表中第一个字符串的第一个字符(即 a )。

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

为什么是我返回的垃圾,当我期望它输出 a ?

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

Thnx任何帮助!

此代码的输出是随机的。它不总是打印相同的字符..:S

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

推荐答案

如果你的目的是通过std的内容: :string到修改char *的内容的函数:

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

更多推荐

为什么我的函数返回的垃圾,当它应该返回一个char?

本文发布于:2023-10-24 21:13:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1525023.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:当它   函数   垃圾   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!