0

hey guys, i have a problem with this program...

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;
    }

i know that the problem is that the compiler is outputting the memory address and not the actual value that i want it to output. how would i change that?
thanks guys

2
Contributors
1
Reply
2
Views
10 Years
Discussion Span
Last Post by Ancient Dragon
0

If you want findMax() to change the value of ptr in main() then you have to pass the parameter by reference and not by value.

void findMax(int arr[], int n, int** pToMax)
 {
    ...
    *pToMax = &arr[0];

}

int main()
{
...
    findMax(nums, 4, &ptr);
}

Or since this is c++

void findMax(int arr[], int n, int*& pToMax)
 {
    ...
    pToMax = &arr[0];

}

int main()
{
...
    findMax(nums, 4, ptr);
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.