C:高级指针操作(多级指针,函数指针) |
您所在的位置:网站首页 › 复合类型数据函数需要多级指针么 › C:高级指针操作(多级指针,函数指针) |
·多级指针
指针是存储地址的特殊变量。那么二级指针也很好理解,即存储指针地址的指针,以此类推。(注意赋值时类型要对应上) ·函数指针函数指针即指向函数的指针 int func(); //...... int (*funp)(); //无传参,返回值为int变量的函数指针 funp = &func;//赋值各种声明例子 int *(*funp)(int,int); int *(*funp[])(int);//funp为函数指针数组,数组元素为函数指针,所指向的函数返回值为int*,传参为int 回调函数即函数参数中有函数指针时,此函数会调用函数指针指向的函数,被调用的这个函数被称为回调函数。 下面这个例子为一个链表中查找是否含有某个值,因为不同类型变量比较方式不同,需要用到函数指针,让用户自己去定义如何对变量进行比较。 #include #include #include struct Node{ struct Node* next; int val; }typedef Node; Node *search_list(Node *node,void const* value,int(*compare)(void const*,void const*)) { while(node!=NULL) { if(compare(&node->val,value)==0)//调用回调函数 break; node = node->next; } return node; } int compare_list(void const* a,void const *b) { if(*(int*)a==*(int*)b) //进行类型转换,这里我们知道要比较的对象为int型。 return 0; else return 1; } int main() { Node* head = malloc(sizeof(Node)); if(head!=NULL) head->val = 100; Node *p = NULL; int val = 10; p = search_list(head,&val,compare_list); if(p!=NULL) printf("find it\n"); else printf("didn't find\n"); free(head); return 0; }参数声明为void*以便于适应查找所有类型的指针,当编写比较函数时,我们知道具体比较对象的类型,此时要进行相应的类型转换。. ·关于void型指针C语言中void * 为 “不确定类型指针”,void *可以用来声明指针,如:void * a,可由它转换为各种类型指针。可以创建void *指针,但不可以创建void型变量。 int main() { int b = 10; void *a = &b; printf("%d\n",*(int*)a); return 0; } |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |