Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a pointer by reference

#include <iostream>

using namespace std;

void merge(int *& toMerge, int lo, int mid, int hi)
{
    int merged[hi+1];
    int i = lo, j = mid+1;
    for (int k = lo; k <= hi; k++)
    {
        if (i > mid) {merged[k] = toMerge[j]; j++;}
        else if (j > hi) {merged[k] = toMerge[i]; i++;}
        else if (toMerge[j] < toMerge[i]) {merged[k] = toMerge[j]; j++;}
        else {merged[k] = toMerge[i]; i++;}
    }
    toMerge = merged;
}

int main(int argc, const char * argv[])
{

    int x[8] = {1,7,4,6,2,7,3,2};
    merge(x, 0, 7, 3);
    return 0;
}

I am trying to pass a pointer by reference here such that the end result will be that the array x will be sorted. However, my compiler is throwing an error that there is no matching function call for the merge(x, 0, 7, 3).

I am not sure as to why this is happening because the merge function requires a pointer, and x is a pointer to the first element in the array -- so it should work. Why doesn't it?

like image 690
1110101001 Avatar asked Nov 26 '25 20:11

1110101001


2 Answers

An array decays to a pointer when you pass it as an argument to a function call but not to a reference to a pointer.

Imagine this:

void foo(int*& p)
{
   p = new int;
}

int main()
{
   int arr[6] = {0};

    foo(arr);
   // You don't want arr to be an invalid object here.
   // If the compiler allowed you to do that, that's what will happen.
   // Not only that, foo(arr); is equivalent to:
   // arr = new int;
   // which is not allowed in the language.
}
like image 71
R Sahu Avatar answered Nov 28 '25 13:11

R Sahu


You really should NOT pass a reference, because you don't really want merge changing the value of the pointer. You just want to allow it to change the values stored in the array, which it can do without the reference (i.e., just from the pointer).

like image 31
Dwayne Towell Avatar answered Nov 28 '25 14:11

Dwayne Towell