您的位置:首页 > 其它

函数指针

2016-04-01 13:26 369 查看
形式: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: