#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;
}我在这里尝试通过引用传递一个指针,这样最终的结果将是数组x将被排序。但是,我的编译器抛出了一个错误,即merge(x, 0, 7, 3)没有匹配的函数调用。
我不确定为什么会发生这种情况,因为merge函数需要一个指针,而x是指向数组中第一个元素的指针--所以它应该可以工作。为什么不是呢?
发布于 2014-06-06 07:43:47
当您将数组作为参数传递给函数调用,而不是传递给指针引用时,数组将衰减为指针。
想象一下:
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.
}发布于 2014-06-06 07:45:11
你真的不应该传递引用,因为你不希望merge改变指针的值。您只希望允许它更改存储在数组中的值,这可以在没有引用的情况下完成(即,仅从指针)。
https://stackoverflow.com/questions/24071969
复制相似问题