繁体   English   中英

如何从函数返回动态分配的指针数组?

[英]How do I return a dynamically allocated pointer array from a function?

我现在在课堂上开始动态内存分配,并且对它有很好的了解,但是不能完全正确地使用它。 我觉得我对指针也可能不太擅长:p

我的讲师给出了创建名为readArray的函数的指令,该函数将提示用户输入要用作大小的数字,以动态创建该大小的整数数组。 然后,我将新数组分配给一个指针。 然后,我应该提示用户填充数组。 然后,我应该返回新创建的数组和大小。

我无法弄清楚如何返回该数组,并且我认为在动态分配内存时,应该在使用该分配以防止泄漏后删除该分配。

数组和大小必须返回给main,以便我可以将其传递给其他函数,例如排序函数。

我将不胜感激,因为我的思考过程不断朝着错误的方向发展。

#include <iostream>
using namespace std;

int* readArray(int&);
void sortArray(int *, const int * );

int main ()
{
   int size = 0;
   int *arrPTR = readArray(size);
   const int *sizePTR = &size;
   sortArray(arrPTR, sizePTR);

   cout<<arrPTR[1]<<arrPTR[2]<<arrPTR[3]<<arrPTR[4];

        system("pause");
        return 0;
}


int* readArray(int &size)
{
   cout<<"Enter a number for size of array.\n";
   cin>>size;
   arrPTR = new int[size];

   for(int count = 0; count < (size-1); count++)
   {    
       cout<<"Enter positive numbers to completely fill the array.\n";
       cin>>*(arrPTR+count);
   }

   return arrPTR;
}

如果使用std::vector<int>则不需要这样做,这是更好的选择。

用它:

std::vector<int> readArray()
{
    int size = 0;
    cout<<"Enter a number for size of array.\n";
    cin >> size;
    std::vector<int> v(size);

    cout<<"Enter "<< size <<" positive numbers to completely fill the array : ";
    for(int i = 0; i < size; i++)
    {   
        cin>> v[i];
    }
    return v;
}

要返回数组,请执行以下操作:将readArray()声明为int* readArray() [返回int*而不是int ],然后返回arrPTR而不是size 这样,您将返回arrPTR指向的动态分配的数组。

关于删除:使用完阵列后,确实应该删除它。 在您的示例中,在main()函数中return 0之前执行此操作。
确保由于使用new[]分配了内存,所以还应该使用delete[]释放它,否则-程序将发生内存泄漏。

就像amit所说的那样,您可能应该返回数组而不是大小。 但是由于您仍然需要大小,因此readArray像这样更改readArray

///return array (must be deleted after)
///and pass size by reference so it can be changed by the function
int* readArray(int &size);

并这样称呼它:

int size = 0;
int *arrPTR = readArray(size);
///....Do stuff here with arrPTR
delete arrPTR[];

更新后:

int* readArray(int size); ///input only! need the & in the declaration to match
                          ///the function body!

是错误的,因为您的实际定义是int &size 您还没有声明arrPTRreadArray ,只是分配给它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM