I understand how pointers and arrays relate to each other though for some reason I am having a hard time grasping an array of pointers.
Basically lets say I have this code:
#include <iostream>
// preforms a selection sort on an array
void SelectionSort(int* arr[], int size);
// Shows the contents of the array passed in
void ShowArray(int* arr, int size);
// Show the contents of the sorted array
void ShowSortedArray(int* arr[], int size);
int main()
{
int donations[5] = {5, 10, 1, 15, 7};
// array of pointers
int* sortedDonations[5];
// before we sort, set it to the unsorted donations
for(int i = 0; i<5; i++)
{
sortedDonations[i] = &donations[i];
}
SelectionSort(sortedDonations, 5);
ShowArray(donations, 5);
std::cout << "Sorted Donations: " <<std::endl;
ShowSortedArray(sortedDonations, 5);
return 0;
}
//preform a selection sort on the passed in array
void SelectionSort(int* arr[], int size)
{
int startScan;
int index;
int minIndex;
int* min;
for(startScan = 0; startScan < size-1; startScan++)
{
min = arr[startScan];
for(index = startScan+1; index<size; index++)
{
if(*arr[index] < *min)
{
min = arr[index];
minIndex = index;
}
}
arr[minIndex] = arr[startScan];
arr[startScan] = min;
}
}
// display an array
void ShowArray(int arr[], int size)
{
for(int i = 0; i<size; i++)
{
std::cout << arr[i] << " ";
}
std::cout<<std::endl;
}
//Display an Array of pointers
void ShowSortedArray(int* arr[], int size)
{
for(int i = 0; i<size; i++)
{
std::cout << *(arr[i]) << " ";
}
std::cout<<std::endl;
}
While I understand what is going on in this code I just don't understand why we must use an array of pointers here?
I understand that the code is running a selection sort on an array without messing with the original array. Though why is it that I need to use an array of pointers? What's actually going on there? I understand the basics of why I guess though I don't think I could go in depth and if someone were to ask me why it used an array of pointers I wouldn't know what to say to them.
Thanks to all who can help...