函数指针的使用

来源:互联网 发布:php一键安装包windows 编辑:程序博客网 时间:2024/05/17 02:55

       函数的类型是由函数的返回值和参数表确定的,另外,函数名即函数的地址,相当于函数的指针。

那么,什么是函数指针呢?简单的说就是指向函数的指针,因为函数也有地址,所以可以通过指针来调用函数,函数指针一般用作参数,参看维基百科上的解释:

struct object{    int data;}; intobject_compare(    struct object * a,    struct object * z){    return a->data < z->data ? 1 : 0;} struct object *maximum(    struct object * begin,    struct object * end,    int (* compare)(struct object *, struct object *)){    struct object * result = begin;     while(begin != end)    {        if(compare(result, begin))        {            result = begin;        }         ++ begin;    }     return result;} intmain(    void){    struct object data[8] = {{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}};    struct object * max;     max = maximum(data + 0, data + 8, & object_compare);     return 0;}

 int (* compare)(struct object *, struct object *)
上面是声明的一个函数指针,在if语句中就通过compare指针来调用该函数的。