如何从函数返回动态分配的指针数组? [英] How do I return a dynamically allocated pointer array from a function?
问题描述
我现在开始在类中的动态内存分配,并有一个确定的理解,但不能完全使用它。我觉得我可能不会这么伟大与指针:p
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
我的教师给了指令创建一个名为readArray的函数,将提示用户一个数字使用大小为动态创建该大小的整数数组。然后我将新数组分配给一个指针。然后我应该提示用户填充数组。然后我应该返回新创建的数组和大小。
My instructor gave instructions to create a function named readArray that will prompt the user for a number to use as a size to dynamically create 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.
我不知道如何返回数组,而我想当动态分配内存你应该在使用它之后删除分配以防止泄漏。
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.
数组和大小必须返回到main,所以我可以将它传递给其他函数,如排序函数。
The array and size must be returned to main so I can pass it to other functions such as a sorting function.
我会非常感谢任何帮助,因为我的思维过程中,这将继续走错了方向。
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;
}
推荐答案
返回数组:declare readArray()
as int * readArray()
[return an int *
而不是大小$>,而不是
int
],并返回 arrPTR
c $ c>。这样,你返回 arrPTR
指向的动态分配的数组。
To return an array: declare readArray()
as int* readArray()
[return an int*
instead of an int
], and return arrPTR
instead of size
. This way, you return the dynamically allocated array which arrPTR
points to.
关于删除:使用数组,你应该删除它。在您的示例中,在 main()
函数中返回0
确保自从您为 new []
分配内存后,您还应该使用 delete []
,否则您的计划将有内存泄漏。
Regarding the delete: When you are done using the array, you should indeed delete it. In your example, do it before return 0
in 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.
这篇关于如何从函数返回动态分配的指针数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!