Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从C+中的函数返回数组+;_C++_Arrays - Fatal编程技术网

C++ 从C+中的函数返回数组+;

C++ 从C+中的函数返回数组+;,c++,arrays,C++,Arrays,我尝试使用下面的代码返回一个包含所有字符串ID的数组,但没有成功。 输出只返回一个数字。如何返回ID为的数组 #include <iostream> #include <string> using namespace std; string* getArray() { int nanim; cout << "Enter the number of animals: "; cin >> nanim; string *id = new

我尝试使用下面的代码返回一个包含所有字符串ID的数组,但没有成功。 输出只返回一个数字。如何返回ID为的数组

#include <iostream>
#include <string>
using namespace std;

string* getArray()
{   
    int nanim;
cout << "Enter the number of animals: ";
cin >> nanim;

string *id = new string[nanim];
for ( size_t i=0; i < nanim; i++ ) 
{
    cout<< "\nEnter id anim "<< i+1 << ": "; 
    cin >> id[i];
    }
    for ( size_t i = 0; i < nanim; i++ ) 
    {
    cout << id[i] << endl; 
    }
return id;
 }

  int main()
{
 int n;
 cin>>n;
    string* anim[n]=getArray();
cout<<anim;
return 0;
}
#包括
#包括
使用名称空间std;
字符串*getArray()
{   
内特纳尼姆;
库特>纳尼姆;
string*id=新字符串[nanim];
对于(大小i=0;icout返回指向数组中第一个元素的指针

要访问刚刚调用了
string*arr=getArray();
的数组元素,可以使用arr[0]、arr[1]、arr[2]等来访问字符串

不过,不要忘记删除在函数中分配的内存;目前您有一个很大的内存泄漏

但通常这不是一个好的编程,因为函数调用方不知道返回数组中有多少元素。最好获取调用方中动物的数量并将其传递到函数中


更好的是,重新构建代码以使用std::vector,因为我看到您已经在使用stl。这样您就不必(明确地)担心内存分配和释放。

您不需要读取两次元素的数量,并且
动画的类型应该是
字符串*
,而不是
字符串*[]
。不幸的是,这不会告诉您数组中的项数,因此您需要从
getArray
获取它,例如:

string* getArray(int& nanim) {
    // Remove the declaration of nanim, and keep the rest of the code unchanged
    ...
}

int main()
{
    int n;
    string* anim = getArray(n);
    for (int i=0; i != n; i++) {
        cout << anim[i] << endl;
    }
    delete[] anim;
    return 0;
}

您没有返回数组,而是返回一个指向数组第一个元素的指针。最好使用
std::vector
。您不能从函数返回数组(或将数组传递给函数)。仅此而已。当然,您可以,您只是不知道长度。@Joel-不,您正在传递(或返回)指向数组的指针。虽然数组将衰减为指针,但它们不是指针。是的,但在这个问题的级别上,您可以从函数返回数组。说不能返回数组只是迂腐的,没有帮助+1。此外,我建议将n传递给getArray()作为一个参数,并对其进行一些合理性检查。好的方面是AlexK+1。就我个人而言,我也不喜欢在函数中分配内存的代码,释放内存是调用方的工作。如何使用向量实现这一点?@user2386222查看编辑。以下是在ideone上运行的相同代码:。
#include <iostream>
#include <string>
#include <vector>
using namespace std;

vector<string> getVector()
{   
    int nanim;
    cout << "Enter the number of animals: ";
    cin >> nanim;
    vector<string> res;
    for ( size_t i=0; i < nanim; i++ ) 
    {
        cout<< "\nEnter id anim "<< i+1 << ": ";
        string tmp;
        cin >> tmp;
        res.push_back(tmp);
    }
    return res;
}

int main()
{
    vector<string> anim = getVector();
    for ( size_t i = 0; i < anim.size(); i++ ) 
    {
        cout << anim[i] << endl; 
    }
    return 0;
}