如何在c/c++函数中返回char*数组
How to return char* array in c/c++ function?
以下是我的函数原型(我们无法更改此函数的原型):
char** myfun()
{
// implementation
}
如何从该函数返回char*数组,以便在该方法的调用方中访问/打印数组的内容。我尝试使用动态内存分配创建一个数组,但它不起作用。
是否可以在没有动态内存分配的情况下做到这一点。请给我指针好吗?
除非你有一个全局char*[],你想从这个函数返回,是的,你需要动态分配,这是你可以安全返回函数内创建的变量的唯一方法,因为函数一结束,堆栈中存储的所有变量都会被销毁。
char** myfun()
{
char **p = new char*[10];
return p;
//or return new char*[10];
}
int main() {
char **pp = test();
char *p = "aaa";
pp[0] = p;
delete[] pp; //if you allocate memory inside the array, you will have to explicitly free it:
//Example: pp[1] = new char("aaa"); would require delete p[1];
}
--编辑
您不必使用动态分配,您可以返回一个本地静态变量。但请记住,这不是一个好方法:函数不会是线程安全的或可重入的。
#include <string>
#include <vector>
#include <iostream>
std::vector<std::string> myfun() {
return {"hello", "vector", "of", "strings"};
}
int main() {
using namespace std;
auto v_of_s = myfun();
for (auto &s : v_of_s) {
cout << s << ' ';
}
cout << endl;
}
实际示例
或者,在旧C++中:
#include <string>
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
std::vector<std::string> myfun() {
std::vector<std::string> v_of_s;
v_of_s.push_back("hello");
v_of_s.push_back("vector");
v_of_s.push_back("of");
v_of_s.push_back("strings");
return v_of_s;
}
int main() {
using namespace std;
vector<string> v_of_s = myfun();
copy(v_of_s.begin(), v_of_s.end(), ostream_iterator<string>(cout, " "));
cout << endl;
}
实例
相关文章:
- 从循环返回char函数数据
- 如何使用 c++ 中的函数返回 char 数组的大小
- 无法使用函数 C++ 返回 char 数组
- 在 c++ 函数中返回 char* 时出错
- C# PInvoke - 返回 char* 和引用 char* 参数的函数
- 如何从 C++ 中的函数返回 char*
- 谁需要释放返回char*的系统调用的内存
- 返回char*变量的地址
- 如何使C++函数返回 char 数组所有排列的向量
- 返回 char* 出错,打印好,返回不好(c++)
- Atoi 仅返回 char* 参数的第一个数字
- Std::string 由返回 char * 的函数赋值
- 如何在c/c++函数中返回char*数组
- 如何调用返回char* (Java中的String和c++中的char*)的方法
- 为什么strrchr()返回' char* '而不是' const char* ' ?
- 从C中的函数返回char数组的首选方式
- 如何从c++返回char **并在Python中使用ctypes将其填充到列表中
- 将异或函数转换为返回char*而不是字符串
- 使用c++从xml文件返回char*以外的数据类型时出错
- 调用从c#返回char*的c++dll函数.无法使用DllImport()