-2 c++ pointers dynamic-memory-allocation
#include <iostream>
using namespace std;
void arrSelectSort(int *[], int), showArrPtr(int *, int);
void showArray(int [] , int);
int main()
{
int numDonations;
int *arrPtr;
cout << "What was the number of donations?: ";
cin >> numDonations;
arrPtr = new int[numDonations];
cout << "What were the donations values?: ";
for (int count = 0; count < numDonations; count++)
cin >> arrPtr[count];
arrSelectSort(arrPtr, 3);
cout << "The donations, sorted in ascending order are: \n";
showArrPtr(arrPtr, 3);
cout << "The donations, in their orginal order are: \n";
showArray(values, 3);
system(" Pause ");
return 0;
}
void arrSelectSort(int *array[], int size)
{
int startScan, minIndex;
int* minElem;
for (startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minElem = array[startScan];
for(int index = startScan + 1; index < size; index++)
{
if (*(array[index]) < *minElem)
{
minElem = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minElem;
}
}
void showArray(int array[], int size)
{
for (int count = 0; count < size; count++)
cout << array[count] << " ";
cout << endl;
}
void showArrPtr(int *array, int size)
{
for (int count = 0; count < size; count++)
cout << *(array[count]) << " ";
cout << endl;
}
Run Code Online (Sandbox Code Playgroud)
这非常令人困惑,我无法弄清楚如何将动态内存分配数组传递给函数.我知道这是可能的,因为这是C++数据包练习的一部分.当我尝试删除electort函数中的括号时,它会给我一些错误.当我试图删除*它给我其他错误.
void arrSelectSort(int *[], int)
Run Code Online (Sandbox Code Playgroud)
第一个参数是类型int**.
你可以这样调用这个函数:
arrSelectSort(arrPtr, 3);
Run Code Online (Sandbox Code Playgroud)
哪里arrPtr是类型int*.这是编译器通知您的类型不匹配.
我认为错误是在声明中arrSelectSort.它应该是:
void arrSelectSort(int[], int)
Run Code Online (Sandbox Code Playgroud)
第一个参数现在是类型int*.这正是你需要的,一个指向数组的指针int.
然后,您在执行过程中遇到了一些其他错误,arrSelectSort但我并不特别想尝试对它们进行全部调试.
你需要做出minElem类型int.在其他几个地方,您需要删除一定程度的间接.例如,这一行:
if (*(array[index]) < *minElem)
Run Code Online (Sandbox Code Playgroud)
应该:
if (array[index] < minElem)
Run Code Online (Sandbox Code Playgroud)
等等.