在C ++函数中返回字符串数组 [英] Return string array in C++ function

查看:113
本文介绍了在C ++函数中返回字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手. 对于学校项目,我需要制作一个能够返回字符串数组的函数.

I am new to C++. For a school project I need to make a function which will be able to return a string array.

当前,我的标题中有这个

Currently I have this in my 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中,这就是做到这一点的方法.我已经尝试过搜索我的问题,但没有发现任何明显的诚实答案.

Obviously this does not work but that's the idea of what I am trying to do. In Java this would be the way to do it. I've tried googling my problem but I didn't come across any answers that were clear to be honest.

推荐答案

在这种情况下,也许最好使用向量,但这并不是该问题的正确答案.它不起作用的原因是变量test仅存在于函数范围内. 因此,您必须自己管理内存.这是一个示例:

Maybe it is better to use a vector in this case, but this is not a correct answer for the question. The reason why it doesn't work is that the variable test just exists in the scope of your function. So you have to manage the memory on your own. Here is an example:

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

 return names;
}

在这种情况下,您将返回堆中该位置的指针.堆中的所有内存都必须手动释放.因此,现在就可以删除内存,如果您不再需要它的话:

In this case you return a pointer of the position in the heap. All the memory in the heap has to free manually. So it is now your work to delete the memory, if you don't need it anymore:

delete[] names;

这篇关于在C ++函数中返回字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆