函数指针

形式:void (*fun_type) (int* a)




//例1,一个简单例子

void f(int *a){
  *a = 2333;
}


int main(){
  void (*pf)(int *a) = &f;


  int a = 5;
  f(&a);
  //下面两种调用方法结果一致,因为编译器使用函数名时总是会将其转换为函数指针,第二种的操作多余
  int b = 6;
  pf(&b);
  int c = 7;
  (*pf)(&c);


  int tt = 0;
  return 0;
}




//例2,函数类型定义后使用函数指针
typedef void (*fun_type) (int* a);


void fun(int *a){
  *a = 2333;
}


int main(){
  fun_type fun_instance = fun;


  //下面两种调用方法结果一致,因为编译器使用函数名时总是会将其转换为函数指针,第二种的操作多余
  int a = 5;
  fun(&a);


  int b = 6;
  (*fun)(&b);


  int tt = 0;
  return 0;
}



//例3,回调函数,查找链表节点
struct Node{
  int the_value;
  Node *node_next;
};


int compare_ints(void const *a, void const *b){
  if (*(int *)a == *(int *)b) //强制类型转换
    return 0;
  return 1;
}


Node *search_list(Node *node, void const *the_value, int (*compare)(void const *a, void const *b)){
  while (node != NULL){
    if (compare(&node->the_value, the_value) == 0)
      break;
    node = node->node_next;
  }
  return node;
}


int main(){
  Node *first = new Node;
  Node *second = new Node;
  Node *third = new Node;


  first->the_value = 1;
  first->node_next = second;
  second->the_value = 2;
  second->node_next = third;
  third->the_value = 3;
  third->node_next = NULL;


  int desired_value = 2;
  Node *desired_node = search_list(first, &desired_value, compare_ints);


  int tt = 0;
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值