c++函数中返回字符串数组

Return string array in C++ function

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

我是c++新手。对于一个学校项目,我需要做一个函数,它将能够返回一个字符串数组。

目前在我的header中有:

Config.h

string[] getVehicles(void);

Config.cpp

string[] Config::getVehicles(){
string test[5];
test[0] = "test0";
test[1] = "test1";
test[2] = "test2";
test[3] = "test3";
test[4] = "test4";
return test;}

显然这不起作用,但这就是我想要做的。在Java中就是这样做的。我试着在谷歌上搜索我的问题,但我没有找到任何答案是明确的,说实话。

也许在这种情况下使用向量更好,但这不是问题的正确答案。它不起作用的原因是变量test只存在于函数的作用域中。所以你必须自己管理内存。下面是一个例子:

string* getNames() {
 string* names = new string[3];
 names[0] = "Simon";
 names[1] = "Peter";
 names[2] = "Dave"; 
 return names;
}

在这种情况下,返回一个指向堆中位置的指针。堆中的所有内存都必须手动释放。所以现在你的工作是删除内存,如果你不再需要它:

delete[] names;

在c++中不使用数组,而是使用std::vector实例。c++中的数组必须有一个编译时固定的长度,而std::vector实例可以在运行时改变它们的长度。

std::vector<std::string> Config::getVehicles()
{
    std::vector<std::string> test(5);
    test[0] = "test0";
    test[1] = "test1";
    test[2] = "test2";
    test[3] = "test3";
    test[4] = "test4";
    return test;
}

std::vector也可以动态增长,所以在c++程序中你会经常发现像

这样的东西
std::vector<std::string> Config::getVehicles()
{
    std::vector<std::string> test; // Empty on creation
    test.push_back("test0"); // Adds an element
    test.push_back("test1");
    test.push_back("test2");
    test.push_back("test3");
    test.push_back("test4");
    return test;
}

动态分配std::string数组在技术上是可能的,但在c++中是一个糟糕的想法(例如c++不提供Java具有的垃圾收集器)。

如果你想用c++编程,那就找一本好的c++书,从头到尾读一遍……用c++编写Java代码是一场灾难,因为这两种语言尽管表面上有大括号的相似之处,但在许多基本方面却非常不同。

试试这个

#include <iostream>
#include <string>
using namespace std;
string * essai()
    {
    string * test = new string[6];
    test[0] = "test0";
    test[1] = "test1";
    test[2] = "test2";
    test[3] = "test3";
    test[4] = "test4";
    cout<<"test et *testt"<<&test<<' '<<*(&test)<<'n';
    return test;
    }
main()
    {
    string * toto;
    cout<<"toto et *totot"<<&toto<<' '<<*(&toto)<<'n';
    toto = essai();
    cout<<"**totot"<<*(*(&toto))<<'n';
    cout<<"totot"<<&toto<<' '<<*(&toto)<<'n';
    for(int i=0; i<6 ; i++)
        {
        cout<<toto[i]<<' '<<&toto[i]<<'n';
        }
    }

例如,在我的计算机中,结果是

toto et *toto   0x7ffe3a3a31b0 0x55dec837ae20
test et *test   0x7ffe3a3a3178 0x55dec9ddd038
**toto  test0
toto    0x7ffe3a3a31b0 0x55dec9ddd038
test0 0x55dec9ddd038
test1 0x55dec9ddd058
test2 0x55dec9ddd078
test3 0x55dec9ddd098
test4 0x55dec9ddd0b8
 0x55dec9ddd0d8

获取地址和地址的内容可以帮助您理解c++中的数组实际上是基本的:它不提供方法,您可以访问索引而不分配内存(循环中的值6)。你的第一个例子显示了一个局部数组(test)的直接分配,所以你不能返回它(局部数组死亡),在这个例子中,局部变量也死亡了,但是总是有一个变量访问分配的内存的这一部分,函数,然后是接收函数结果的变量,所以变量test在调用函数后死亡,但内存仍然被分配。问候。