函数参数
我们在实际函数处理过程中,经常用到函数来解决实际问题。而函数作为参数调用也是提升代码简洁性以及可重复使用的重要手段,今天就此讲下自己的看法和理解。
函数指针
函数指针: 指向函数的指针。指针指向的是地址,而函数名是作为函数入口地址来实现的,因此我们可以通过定义一个函数指针来指向函数。
函数指针定义 :
- 常规方法:
#include<stdio.h>
int max(int a, int b) {
return a > b ? a : b ; /*问号表达式:当a大于b时,结果为真输出a即第一项,否则输出第二项; True ? 第一项: 第二项*/
}
int (*p)(int a, int b); /*定义指针函数,无任何指向*/
p = max; /* 该指针p指向函数max, 此时p才有了具体的指向max函数的地址*/
int main(){
int maxValue=0, xx=0, yx=0;
printf("please input two number (integer):\n");
scanf("%d%d", &xx, &yy); /*输入两个整型值 */
maxValue=(*p)(xx, yy);
printf("the max number is ", maxValue);/*打印比较之后的最大值*/
return 0;
}
- 非常规方法:
#include <stdio.h>
typedef int (*p)(int a, int b); /*使用该方式重定义该数据类型*/
int max(int a, int b) {
return a > b ? a : b ;
}
p = max;
int main(){
int maxValue=0, xx=0, yx=0;
printf("please input two number (integer):\n");
scanf("%d%d", &xx, &yy); /*输入两个整型值 */
maxValue=(*p)(xx, yy);
printf("the max number is ", maxValue);/*打印比较之后的最大值*/
return 0;
}
使用方式
比如我们实现函数进行多项式计算:f(x) = a0 + a1x + a2x2 + a3x3 + …;比较两种方法的计算时间,那个算法时间效率更好。
#include <stdio.h>
#include <time.h>
#include <math.h>
clock_t start, stop;
double duration;
#define MAXN 10 /* 多项式最大项数,即多项式阶数+1 */
#define MAXK 1e7 /* 多项式迭代次数,即10000000次 */
typedef double(*Func)(int n, double a[], double x) ; /*定义指针函数*/
double MyFunction1(int n, double a[], double x); /*函数声明*/
double MyFunction2(int n, double a[], double x); /*函数声明*/
void showTime (Func fc, double a[]); /*函数声明, 并引用函数指针作为参数*/
int main (){
int i;
double a[MAXN]; /*定义数组a*/
for ( i = 0; i < MAXN; i++)
{
a[i] = (double) i; /*初始化数组a*/
}
showTime(MyFunction1, a); /*调用函数1进行时间效率的计算*/
showTime(MyFunction2, a);/*调用函数2进行时间效率的计算*/
getchar();
return 0 ;
}
void showTime (Func fc, double a[]){ /*调用函数进行时间效率的计算*/
double xx=0.0;
start = clock(); /*初始时间*/
for (int i = 0; i < MAXK; i++) /*设置maxk足够大,是为了保证实验计算是在多个trick中进行的,否则的输出结构为0.*/
{
xx = (* fc)(MAXN-1, a, 1.1);
}
stop = clock(); /*结束时间*/
printf("clk_tck: %d", CLK_TCK); /*不同的机器,时钟trick不同*/
duration = ((double)(stop - start))/CLK_TCK/MAXK; /*计算时间*/
printf("ticks1: %f\n", (double)(stop-start));
printf("duration1: %6.2e\n", duration);/*打印每次运行的时间*/
return;
}
double MyFunction1 (int n, double a[], double x){ /*函数1 进行多项式计算*/
int i;
double p=a[0]; /*设置初始值a0*/
for ( i = 1; i <= n ; i++)
{
p += (a[i] * pow(x, i)); /*从a0一直加到最后*/
}
return p;
}
double MyFunction2 (int n, double a[], double x){
int i;
double p=a[n]; /*设置初始值an*/
for ( i = n; i > 0 ; i--)
{
p = a[i-1] + x*p; /*f(x) = a0 + x*(a1 + x*(a2 +...))*/
}
return p;
}
结论
使用指针函数,可以重复使用代码片段,节省时间,提高效率。谨以此纪念所学。
样例基于中国大学慕课这家大学数据结构第三小节所改。