将功能传递给功能C

我目前正在训练自己如何将函数作为参数进行传递,但是我无法使我的逻辑起作用。希望你们中的一个能提供帮助!

我有一个名为“ square”的函数,该函数接受一个int并返回其平方。

然后,我还有另一个名为“ map”的函数,该函数将一个数字列表和平方函数作为输入,并且我想将每个这些数字平方在map函数中。

我在main中声明了指向平方函数的指针,但是由于它将int作为参数,因此它只是将列表中所有数字的初始整数平方。我如何将函数分配给变量,例如,当我将其传递给map函数时,我可以更改将int传递给Square函数的方式

int b = 1; //Global variable

int square (int x) {
  return x*x;
}
int map (struct node *head,int x) {
int z = head->data; //this variable is what i want squared.

// If i call x here itll use the b variable and square that. 
//changing b doesnt work either since it takes the value that b had when map function was called
if (head->next == NULL) {
    return 0;
  }
  else {
    printf("Value: %d",z)
    map(head->next,x);

  }
  return 0;
}

int main(void) {
int (*sf)(int); 
sf = square; //Assigning the square function to the sf variable
int x =(*sf)(b); //here is the problem,b is the variable thatll get squared every time my function runs
map(head,x); //passing x (square function) and head of a linked list


yaoyuan_1111 回答:将功能传递给功能C

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3121606.html

大家都在问