指向函数的指针&指针函数

指向函数的指针&指针函数

一、函数指针实例

# include <stdio.h>
# include <time.h>
# include <math.h>
# define MAXN 101	// 多项式最大项数
# define MAXK 1e4	// 被测函数最大重复调用次数

clock_t start, stop;

double duration;

double f1(int n, double a[], double x);

double f2(int n, double a[], double x);

// 计算时间函数
void fun_time(double (*p)(), double *a) {          //  double (*p)():函数指针。指向函数的指针,括号内的参数类型可以省略。
// void fun_time(double (*p)(int, double *, double), double a[MAXN]) {

	double result;
    start = clock();

	for (int i = 0; i < MAXK; i++)	// 重复调用以获得充分多的时钟打点数

		result = p(MAXN - 1, a, 1.1);

	stop = clock();

	duration = ((double)(stop - start)) / CLK_TCK / MAXK;	// 计算运行时间
    
    printf("result of %p is %f\n", p, result);

    printf("ticks = % f\n", (double)(stop - start));

	printf("duration = % 6.2e\n", duration);

}

int main() {

	int i;

	double a[MAXN];		// 存储多项式系数

	a[0] = 1;
    for (i = 1; i < MAXN; i++) a[i] = (double)1/i;

    printf("address(f1) is %p\n", f1);
    printf("address(f2) is %p\n", f2);

	fun_time(f1, a);	// 回调函数,计算时间

	fun_time(f2, a);

	return 0;

}

double f1(int n, double a[], double x){
    double sum = a[0];
    for(int i=1;i<=n;i++){
        sum += a[i]*pow(x,i);
    }
    return sum;
}

double f2(int n, double a[], double x){
    double sum = a[n];
    for(int i = n; i>0; i--){
        sum = a[i-1]+x*sum;
    }
    return sum;
}

输出如下:

address(f1) is 00007FF785B52A81
address(f2) is 00007FF785B51C6C
result of 00007FF785B52A81 is 1722.444814
ticks = 26.000000
duration = 2.60e-06
result of 00007FF785B51C6C is 1722.444814
ticks = 3.000000
duration = 3.00e-07

二、函数指针作为函数的返回值

#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
 
//即上面需要返回的BFunction函数,执行加法操作
int add(int a, int b)
{
	return a + b;
}
 
int (*AFunction(const char * ch, int(*p)(int, int)))(int a,int b) //实际上就是 int (*p)(int,int)
{
	if (strcmp(ch,"add") == 0)  //只有传入“add”的时候才返回加法函数,否则返回null
	{
		return p;
	}
	else
	{
		return NULL;
	}
}
 
 
int main()
{
	//返回的类型要与定义的BFunction兼容
	int(*p)(int, int) = AFunction("add", add);
	int result;
	result = p(100, 20);
	printf("the result is : %d\n", result);
 
	// getchar();
	return 0;
}

参考链接:https://blog.csdn.net/qq_27825451/article/details/103081289

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

史迪仔的粉红泡泡空间

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值