#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?
xis an array, not a pointer. - chrismerge(&x[0], 0, 7, 3);also work? - Cyclonecodexdecays into a pointer to the first element. See arrays. While I'm talking, I should point out thatint merged[hi+1];is invalid because the size is not a compile time constant. - chrismainthat is an lvalue (like a separate variable). Or you can change it to usestd::vector(since the function won't work properly withstd::arraywithout 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