函数指针总结

实习期间遇到的代码中很多地方用到了函数指针,因为我需要改代码架构,这个我必须会hhhh,特意总结一下:

大家应该都用过指针型函数,比如int * max(int a,int b),这个函数的意思是:返回值是int型指针的函数。但是(敲黑板)接下来的就不一样了,int (*max)(int a,int b),这样就代表是一个函数指针,

看几个例子:

#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 a,int b);
	if(flag == GET_MAX)
		p = get_max;
	else
		p = get_min;
	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 ;

}


#include <stdio.h>
#include <string.h>

void check(char *a,char *b,int (*cmp)(const char *,const char *));

main()
{
    char s1[80]="hello",s2[80]="world";
    int (*p)(const char *,const char *);

	//将库函数strcmp的地址赋值给函数指针p
    p=strcmp;

    //printf("Enter two strings.\n");
    //gets(s1);
    //gets(s2);

    check(s1,s2,p);
}

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");
}

#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);

main()
{
    char s1[80]="hello",s2[80]="world";

   /* printf("Enter two values or two strings.\n");
    gets(s1);
    gets(s2);*/

	//如果是数字,则用函数指针传入数字比较函数进行处理
    if(isdigit(*s1)){
        printf("Testing values for equality.\n");
        check(s1,s2,compvalues);
    }
	//如果是字符串,则用函数指针传入库函数strcmp进行处理
    else{
        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;
}

这篇文章参考了:https://blog.csdn.net/str999_cn/article/details/78591369

猜你喜欢

转载自blog.csdn.net/salmonwilliam/article/details/82080265