我被要求编写一个代码,使用指针将 3 个输入的整数重新排列为升序/降序。
我需要使用函数 order()
返回指向函数 ascending3()
或 descending()
的指针,具体取决于输入的“e”值是多少。
我一直在 readInts() 函数指定的行上收到错误,我不确定如何修复它。
错误
lvalue required as unary ‘&’ operand" -- The error for `ptr = &(order(e))`
warning: assignment makes pointer from integer without a cast -- The error for `ptr=order(e)`
指针代码
void readInts(){
int *a,*b,*c;
char e;
int (*ptr1)(int*,int*,int*);
int result;
printf("Enter Integer 1:");
scanf("%d", a);
printf("Enter Integer 2:");
scanf("%d", b);
printf("Enter Integer 3:");
scanf("%d", c);
printf("Enter either A or D:");
scanf(" %c", &e);
ptr1 = &(order(e)); /*ERROR HERE*/
result = (*ptr1)(a,b,c);
printf("%d %d %d", a, b, c);
}
函数
int ascending3(int* x, int* y, int* z)
{
/*removed sorting code for the sake of shortening the question*/
*x=smallest;
*y=middle;
*z=largest;
}
int descending(int* x, int* y, int* z)
{
int swap;
ascending3(x,y,z);
swap=*x;
*x=*z;
*z=swap;
}
int (*order(char e))(int*x ,int*y,int*z)
{
if(e=='a')
{
return ascending3;
}
else if(e =='d')
{
return descending;
}
return;
}
最佳答案
函数不能返回函数。因此,您不能将 address of
运算符 (&
) 应用于函数的结果(以检索地址)。但是函数可以返回指向函数的指针。
C 中函数的名称(是否以 &
运算符为前缀)始终设置为函数的地址,即指向该函数的指针。
正确的代码是:
int ascending3(int *x, int *y, int *z);
int descending(int *x, int *y, int *z);
typedef int (*fn)(int *x, int *y, int *z);
fn order(char e)
{
if (e == 'a')
{
return ascending3;
}
else if (e == 'd')
{
return descending;
}
return NULL;
}
void readInts(void)
{
int *a, *b, *c;
char e;
fn ptr1;
int result;
printf("Enter Integer 1:");
scanf("%d", a);
printf("Enter Integer 2:");
scanf("%d", b);
printf("Enter Integer 3:");
scanf("%d", c);
printf("Enter either A or D:");
scanf(" %c", &e);
ptr1 = order(e);
result = (*ptr1) (a, b, c);
printf("%p %p %p", a, b, c);
}
我使用 typedef
来声明我们的函数指针 的类型(以及排序函数的 2 个原型(prototype))。
如果你喜欢用星号来更好地显示我们类型的指针性质,你可以将 fn
定义为函数(而不是指向函数的指针):
typedef int (fn)(int *x, int *y, int *z);
因此您可以使用星号表示法:
typedef int fn(int *x, int *y, int *z);
fn *order(char e)
{
if (e == 'a')
{
return ascending3;
}
else if (e == 'd')
{
return descending;
}
return NULL;
}
void readInts(void)
{
int *a, *b, *c;
char e;
fn *ptr1;
int result;
printf("Enter Integer 1:");
scanf("%d", a);
printf("Enter Integer 2:");
scanf("%d", b);
printf("Enter Integer 3:");
scanf("%d", c);
printf("Enter either A or D:");
scanf(" %c", &e);
ptr1 = order(e);
result = (*ptr1) (a, b, c);
printf("%p %p %p", a, b, c);
}
关于c - 返回指向函数错误的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32244947/