c++函数中返回字符串数组
Return string array in C++ function
我是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在调用函数后死亡,但内存仍然被分配。问候。
- 将C#字符串数组传递给C++
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 尝试将 c 字符串数组与分隔符连接起来
- 将字符串数组传递给接受常量字符**的函数
- 返回 C++ 中的字符串数组
- 如何从COM模块中的函数返回字符串数组?
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 删除字符串数组
- 如何将字符串数组返回到 java JNI
- 将字符串数组作为函数参数传递
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 乘以字符串/数组和全局数组
- 递归二进制搜索与字符串数组
- 如何初始化一个标准::字符串数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++字符串数组的动态向量
- 给定一个等长字符串数组