将指向数组的指针作为函数参数传递,这本身就是另一个函数的返回值?

Pass pointer to array as function argument, which itself is return value of another function?

本文关键字:函数 另一个 返回值 参数传递 数组 指针      更新时间:2023-10-16

>我有两个重载函数:"ChooseElements",它从传递的数组中选择元素,以及"SortElements",它对传递数组的元素进行排序。一对使用 INT 数据,另一对处理 FLOAT。

int * ChooseElements(int * X, int n, int & m)
{
int * Y = NULL;
for (int i = 0; i < n; i++)
{
if (X[i] > 0)
{
if (Y == NULL)
{
m = 1;
Y = new int[1];
Y[0] = X[i];
}
else
{
m++;
Y = (int *)realloc(Y, sizeof(int) * m);
Y[m - 1] = X[i];
}
}
}
return Y;
}
float * ChooseElements(float * X, int n, int & m)
{
float * Y = NULL;
for (int i = 0; i < n; i++)
{
if (X[i] > 0)
{
if (Y == NULL)
{
m = 1;
Y = new float[1];
Y[0] = X[i];
}
else
{
m++;
Y = (float *)realloc(Y, sizeof(float) * m);
Y[m - 1] = X[i];
}
}
}
return Y;
}

int * SortElements(int m, int *& Y)
{
for (int i = 1; i < m; i++)
{
for (int j = 0; j < m - i; j++)
{
if (Y[j] > Y[j + 1])
{
int Temp = Y[j];
Y[j] = Y[j + 1];
Y[j + 1] = Temp;
}
}
}
return Y;
}
float * SortElements(int m, float *& Y)
{
for (int i = 1; i < m; i++)
{
for (int j = 0; j < m - i; j++)
{
if (Y[j] > Y[j + 1])
{
float Temp = Y[j];
Y[j] = Y[j + 1];
Y[j + 1] = Temp;
}
}
}
return Y;
}

我想做的是将第一个函数作为参数传递给第二个函数。诸如此类:

int n, m;
int * X = NULL, * Y = NULL;
/* ...
Some code in which n and X are initialized
... */
Y = SortElements(m, ChooseElements(X, n, m));

但是,当我尝试这样做时,Visual Studio 2017告诉我:

没有重载函数"SortElements"的实例与参数列表匹配

参数类型为:(int, int *(

如果我这样做:

Y = ChooseElements(X, n, m);
Y = SortElements(m, Y);

一切正常。

如果我删除重载并只留下 INT 对并再次尝试

int n, m;
int * X = NULL, * Y = NULL;
/* ...
Some code in which n and X are initialized
... */
Y = SortElements(m, ChooseElements(X, n, m));

我遇到了另一个问题:

int *ChooseElements(int *X, int n, int &m(

参考非常量值的初始值必须是左值

我做错了什么?我的老师要求一个使用另一个函数作为参数的函数。我写的东西不起作用,我不知道在这里可以做什么。

在你的int * SortElements(int m, int *& Y)您正在使用的函数:int *& Y。所以你有一个对 int 指针的引用。我的猜测是你不需要那个。 您可以只使用 int * Y 作为参数作为解决方案。

Int *& Y - 需要一个左值(如变量 Y(,但 ChooseElements 函数只返回一个临时对象(rvalue(,因为您是按值返回的。