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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9314089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:39:06  来源:igfitidea点击:

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

c++arrayspointersdynamic

提问by sircrisp

I am now starting Dynamic Memory Allocation in class and have a ok understanding of it but can't completely use it properly. I feel like I may not be so great with pointers either :p

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

My instructor gave instructions to create a function named readArray that will prompt the user for a number to use as a size to dynamicallycreate a integer array of that size. I am then to assign the new array to a pointer. I then am supposed to prompt the user to fill the array. I then am supposed to return both the newly created array and the size.

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

I can not figure out how to return the array though, and I thought when dynamically allocating memory you were supposed to delete the allocation after using it to prevent leaks.

我不知道如何返回数组,我想在动态分配内存时你应该在使用它后删除分配以防止泄漏。

The array and size must be returned to main so I can pass it to other functions such as a sorting function.

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

I would greatly appreciate any help I can get as my thought process with this keeps going in the wrong direction.

我非常感谢我能得到的任何帮助,因为我的思考过程一直朝着错误的方向发展。

#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;
}

回答by Nawaz

You would not need to do that if you use std::vector<int>which is far superior choice.

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

Use it:

用它:

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;
}

回答by amit

To return an array: declare readArray()as int* readArray()[return an int*instead of an int], and return arrPTRinstead of size. This way, you return the dynamically allocated array which arrPTRpoints to.

返回一个数组:声明readArray()int* readArray()[return anint*而不是int],并 returnarrPTR而不是size。这样,您返回arrPTR指向的动态分配的数组。

Regarding the delete: When you are done using the array, you should indeed delete it. In your example, do it before return 0in your main()function.
Make sure that since you allocated memory with new[], you should also free it with delete[], otherwise - your program will have a memory leak.

关于删除:当您使用完数组后,您确实应该删除它。在您的示例中,请先return 0在您的main()函数中执行此操作。
确保因为你用 分配了内存new[],你也应该用 来释放它delete[],否则 - 你的程序会出现内存泄漏。

回答by crashmstr

Like amit says, you should probably return the array instead of size. But since you still need the size, change readArraylike so:

就像 amit 说的,你应该返回数组而不是大小。但是由于您仍然需要大小,请readArray像这样更改:

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

and call it like this:

并这样称呼它:

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

After update:

更新后:

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

Is wrong, since you have your actual definition with the int &size. You also don't declare arrPTRin readArray, just assign it.

是错误的,因为您对int &size. 你也不声明arrPTRin readArray,只是分配它。