3
votes
#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?

2
x is an array, not a pointer. - chris
Shouldn't merge(&x[0], 0, 7, 3); also work? - Cyclonecode
@KristerAndersson I already tried that -- didn't work - 1110101001
@user2612743, x decays into a pointer to the first element. See arrays. While I'm talking, I should point out that int merged[hi+1]; is invalid because the size is not a compile time constant. - chris
@user2612743, You need a pointer in main that is an lvalue (like a separate variable). Or you can change it to use std::vector (since the function won't work properly with std::array without some changes). Anyway, &x[0] is not an lvalue. It's a nameless temporary, which can't bind to a reference (it gets destroyed at the end of the function call anyway, so there's no point). And C++11 did not. Not even C++14. Compile with -pedantic. - chris

2 Answers

4
votes

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.
}
1
votes

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).