pointer

Hey i have a function that is supposed to find the position of a max value in an array as well as its value but it keeps getting an error when run does anyone know why?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  void findMax(int arr[], int n, int* pToMax)
    {
        if (n <= 0) 
            return;
    
        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;
    }
Your findMax() function does not return the value of pToMax.
Since you do not initialize ptr in main(), it gets a random value and when you try to display the value you get a segfault.

The easiest way to correct that is to replace
void findMax(int arr[], int n, int* pToMax)
with
void findMax(int arr[], int n, int*& pToMax)
Great that worked... sorry just trying to understand it a little better though. What type of variable is int*& ? And how can you pass a pointer to a parameter that takes this type of variable if its not the same as a pointer?
What you want is to modify the pointer's value that is passed to the function.

In a pure C way, you'd have to pass a pointer to what you want to modify. That means you'd have to write findMax(nums, 4, &ptr); and void findMax(int arr[], int n, int** pToMax)

In C++ the same thing can be achieved by saying your function is passed a reference to the variable. That's what void findMax(int arr[], int n, int*& pToMax) does.
Last edited on
Topic archived. No new replies allowed.