转移表(函数指针数组)和回调函数(通过函数指针调用的函数)

上一篇文章简单介绍了函数指针函数指针数组,本篇文章是介绍他们的用途。

函数指针数组的用途-----转移表:通过转移表来实现一个简单的计算器
代码如下:
#define _CRT_SECURE_NO_WARNINGS 0
#include<stdio.h>
#include<stdlib.h>

int Add(int x, int y)
{
	return x + y;//加
}

int Sub(int x, int y)
{
	return x - y;//减
}

int Mul(int x, int y)
{
	return x * y;//乘
}

int Div(int x, int y)
{
	return x / y;//除
}
void menu()
{
	printf("******1.Add     2.Sub      3.Mul***********************\n");
	printf("***********4.Div       0.Exit   ***********************\n");
}//菜单
void test()
{
	int input=1;
	int x;
	int y;
	int ret = 0;
	int(*p[5])(int, int) = { NULL,Add,Sub,Mul,Div };//函数指针数组
	while (input)
	{
		menu();
		printf("请选择:");
		scanf("%d", &input);
		if (input > 0 && input < 5)
		{
			printf("请输入操作数:");
			scanf("%d%d", &x, &y);
			ret = (*p[input])(x, y);//利用函数数组指针进行调用
			printf("%d\n", ret);
		}
		else
			printf("输入错误!\n");
	}	
}
int main()
{
	test();
}

回调函数:回调函数是一个通过函数指针调用的函数,回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方进行调用,用于对该事件或条件进行响应。
应用:模拟实现qsort(采用冒泡的方式)
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Stu
{
	int age;
	char name[20];
};//定义结构体变量

int comp_int(const void *e1,const void *e2)
{
	return (*(int *)e1) - (*(int *)e2);
}//整型的比较

int comp_student_byname(const void *e1, const void *e2)
{
	return strcmp((*(struct Stu *)e1).name, (*(struct Stu *)e2).name);
}//按名字进行比较

int comp_student_byage(const void *e1, const void *e2)
{
	return (*(struct Stu *)e1).age - (*(struct Stu *)e2).age;
}//按年龄进行比较

void swap_(char *e1, char *e2, int width)
{
	int i = 0;
	for (i = 0; i < width; i++)
	{
		char tmp = *(e1+i);
		*(e1 + i) = *(e2 + i);
		*(e2 + i) = tmp;
	}
}//进行交换

void bubble_sort(void *arr,int width, int sz,int(*compar)(const void *e1,const void *e2))
{
	int i = 0;
	for (i = 0; i < sz - 1; i++)
	{
		int j = 0;
		for (j = 0; j < sz - 1 - i; j++)
		{
			if (compar((char *)arr+j*width,(char *)arr+(j+1)*width)>0)
			{
				swap_((char *)arr + j*width, (char *)arr + (j + 1)*width,width);
			}
		}
	}
}//利用回调函数进行排序

int main()
{
	int arr[] = { 9,8,7,6,5,4,3,2,1,0 }; 
	struct Stu student[3] = { { 18,"lisi"},{20,"zhangsan" },{10,"wamgwu"} };
	int sz = sizeof(arr) / sizeof(arr[0]);
	int sz1 = sizeof(student) / sizeof(student[0]);
	bubble_sort(arr, sizeof(arr[0]),sz,comp_int);
	bubble_sort(student, sizeof(student[0]), sz1, comp_student_byname);
	//bubble_sort(student, sizeof(student[0]), sz1, comp_student_byage);
	system("pause");
	return 0;
}

 
 

猜你喜欢

转载自blog.csdn.net/zimituanzi_/article/details/79585352
今日推荐