I am having trouble figuring out how to fix an error WITHOUT changing anything in the main routine, as the instructions say. The compiler gives me an error on line 20, the line in the main routine that calls the findMax function, because ptr is being used without being initialized.
I don't understand why the compiler says that ptr is not being initialized, because in the findMax function, pToMax is set equal to arr.
I tried making pToMax a pointer to ptr by changing its initialization to int** pToMax and adding * to all subsequent instances of pToMax in the findMax function. However, after I did this, the compiler said that it cannot convert from int* to int** on line 20.
The only other fix I could think of would be to initialize int* ptr to nullptr in the main routine, but the instructions say I am not allowed to modify the main routine.
void findMax(int arr[], int n, int* pToMax)
{
if (n <= 0)
return; // no items, no maximum!
pToMax = arr;
for (int i = 1; i < n; i++)
{
if (arr[i] > *pToMax)
pToMax = arr + i;
}
}
int main()
{
int nums[4] = { 5, 3, 15, 6 };
int* ptr;
findMax(nums, 4, ptr);
cout << "The maximum is at address " << ptr << endl;
cout << "It's at position " << ptr - nums << endl;
cout << "Its value is " << *ptr << endl;
}
pToMaxby-value. Either return it as the function return value or pass it by address (int **ppToMax) and code it appropriately therein.coutkind of gives it away :)