如何在c/c++函数中返回char*数组

How to return char* array in c/c++ function?

本文关键字:返回 char 数组 函数 c++      更新时间:2023-10-16

以下是我的函数原型(我们无法更改此函数的原型):

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

实例