C language function pointer

The Definition: 类型 (*指针变量名)(参数列表);
For example:int (*p)(int i,int j);

Where int is the return type of the function, * p is a pointer to a function, (int i, int j); is a function of the parameters


Note: int F (I int, int J);
int (
P) (I int, int J);
the former is a function that returns a pointer; the latter is a pointer to a function.

Example 1

#include <stdio.h>
 
#define  GET_MAX    0
#define  GET_MIN    1
 
int get_max(int i,int j)
{
    return i>j?i:j;
}
 
int get_min(int i,int j)
{
    return i>j?j:i;
}
 
int compare(int i,int j,int flag)
{
    int ret;
 
    //这里定义了一个函数指针,就可以根据传入的flag,灵活地决定其是指向求大数或求小数的函数
    //便于方便灵活地调用各类函数
    int (*p)(int,int);
 
    if(flag == GET_MAX)
    {
        p = get_max;
    }else{
        p = get_min;
    }
    ret = p(i,j);//或者ret =  (*p)(i,j);
    return ret;
}
 
int main()
{
    int i = 5,j = 10,ret;
    ret = compare(i,j,GET_MAX);
    printf("The MAX is %d\n",ret);
    ret = compare(i,j,GET_MIN);
    printf("The MIN is %d\n",ret);
    return 0 ;
}

Example 2 function pointer as a parameter

/**
    比较两个字符串,相等返回Equal,不相等返回Not Equal
**/
#include <stdio.h>
#include <string.h>
 
void check(char *a,char *b,int (*cmp)(const char *,const char *));
 
int main()
{
    char s1[80],s2[80];
    int (*p)(const char *,const char *);
 
    //将库函数strcmp的地址赋值给函数指针p
    p=strcmp;
 
    printf("请输入两个字符串.\n");
    gets(s1);
    gets(s2);
 
    check(s1,s2,p);
    return 0;
}
 
void check(char *a,char *b,int (*cmp)(const char *,const char *))
{
    printf("Testing for equality.\n");
    //表达式(*cmp)(a,b)调用strcmp,由cmp指向库函数strcmp(),由a和b作调用strcmp()的参数。
    //调用时,与声明的情况类似,必须在*cmp周围使用一对括号,使编译程序正确操作
    if((*cmp)(a,b)==0)
        printf("Equal\n");
    else
        printf("Not Equal\n");
}

Example 3


#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
 
//check()函数的第3个函数是函数指针,就可以根据具体情况传入不同的处理函数
void check(char *a,char *b,int (*cmp)(const char *,const char *));
 
//自定义的比较两个字符串的函数
int compvalues(const char *a,const char *b);
 
int main()
{
    char s1[80],s2[80];
    printf("输入两个数字或自妇产\n");
    gets(s1);
    gets(s2);
    if(isdigit(*s1)){   //如果是数字,则用函数指针传入数字比较函数进行处理
        printf("Testing values for equality.\n");
        check(s1,s2,compvalues);
    }else{//如果是字符串,则用函数指针传入库函数strcmp进行处理
        printf("Testing strings for equality.\n");
        check(s1,s2,strcmp);
    }
}
 
void check(char *a,char *b,int (*cmp)(const char *,const char *))
{
    if((*cmp)(a,b)==0)
        printf("Equal.\n");
    else
        printf("Not Equal.\n");
}
 
int compvalues(const char *a,const char *b)
{
    if(atoi(a) == atoi(b))
        return 0;
    else
        return 1;
}

Guess you like

Origin www.cnblogs.com/cuianbing/p/11580689.html