void findMax(int arr[], int n, int* pToMax)
    {
        if (n <= 0) 
            return;      // no items, no maximum!
    
	int max = arr[0];
	pToMax = &arr[0];
	
	for (int i = 1; i < n; i++)
	{
	    if (arr[i] > max)
	    {
	         max = arr[i];
	         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 index " << ptr - nums << endl;
        cout << "Its value is " << *ptr << endl;
    }

It shows some error. I don't understand. I need to change the findMax function only. I cannot change the main function
Is there anyone tho can explain me why?

Thank You!!^_^

pToMax = &arr[0];

//should be
pToMax = &arr;

>I cannot change the main function
Sucks for you then, because the error is in main and can't be fixed from findMax. You have an uninitialized pointer.

>pToMax = &arr[0];
>//should be
>pToMax = &arr;

No, that changes the the meaning of the expression and introduces a type mismatch. It should be either pToMax = &arr[0] or pToMax = arr .

This is the question for the code up there:

The findMax function is supposed to find the maximum item in an array and set the pToMax parameter to point to that item so that the caller knows its location. Why won't this function do that, and how can it be fixed? Your fix must be to the function only; you must not change the way the function is called in the main routine below (so, for example, you must not change the return type from void).

So is there really nothing i can do to the findMax function to fix the problem?

>So is there really nothing i can do to the findMax function to fix the problem?
No. In keeping with the spirit of the function as well as the question, the solution is to make pToMax a pointer to a pointer. Most of the changes for that are made in findMax, but you still need to make at least one change in main (passing the address of ptr), or the solution won't work. To be a robust solution, main should also initialize ptr to NULL and check for NULL as a failure state.

All in all this is a bogus exercise because it's unsolvable with the given restrictions.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.