sir*_*isp 1 c++ arrays pointers dynamic
我现在正在课堂上开始动态内存分配并对它有一个正确的理解,但不能完全正确使用它.我觉得我的指针可能也不是那么好: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;
}
Run Code Online (Sandbox Code Playgroud)
如果你使用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;
}
Run Code Online (Sandbox Code Playgroud)