![](/img/trans.png)
[英]How to modify and pass array pointer as argument to a function which require array as argument?
[英]Pass pointer to array as function argument, which itself is return value of another function?
我有兩個重載函數:“ 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函數僅返回一個臨時對象(右值),因為您要按值返回。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.