高级指针
int f //整形变量
int *f //整形指针变量
int *f,g
int f() //返回int的函数
int *f() //返回int *的函数
int (*f)() //返回int函数指针
int f[] //int 数组
int *f[] //int*元素数组,也就是指针数组?
Int (*f[])() //返回int函数指针数组
int *(*f[])() //返回int *函数指针数组
函数指针
指向函数存放地址的指针
* &对其无影响,既不修改内容,也不修改偏移量。
默认偏移量为1
对函数指针进行算数运算+ – ,不能偏移至其它函数的地址
转移表
基本计算器的实现
#include<stdio.h>
#include<assert.h>
double add(double x,double y)
{
return x+y;
}
double sub(double x,double y)
{
return x-y;
}
double div(double x,double y)
{
assert(y != 0);
return x/y;
}
double mul(double x,double y)
{
return x*y;
}
//函数指针数组
double (*opFun[])(double,double) =
{
add,sub,mul,div
};
char ops[] =
{
‘+’,’-‘,’*’,’/’
};
double oper(double x,double y,double(*opFun)(double,double))
{
return opFun(x,y);
}
int main(void)
{
double x=0,y=0,ret;
char op=’\0′;
printf(“Please input your exp:”);
scanf(“%lf%c%lf”,&x,&op,&y);
int i;
int len = sizeof(ops)/sizeof(ops[0]);
for(i=0;i<len;i++)
{
if(ops[i] == op)
{
//命中匹配的运算符
ret = oper(x,y,opFun[i]);
break;
}
}
if(i == len)
{
printf(“Unkown operator\n”);
exit(1);
}
printf(“Done: %lf %c %lf = %f\n”,x,op,y,ret);
return 0;
}
fun_funp.c
#include<stdio.h>
int fun1()
{
printf(“by fun1\n”);
}
int fun2()
{
printf(“by fun2\n”);
}
void out_fun(void (*fp)(),int n)
{
printf(“n:%d\n”,n);
fp();//这种形式呢就称为回调过程callback
}
int main(void)
{
out_fun(fun1,100);
return 0;
}
funp.c
#include<stdio.h>
int fun1(int n)
{
printf(“n in fun1:%d\n”,n);
return 1;
}
int fun2(int n)
{
printf(“n in fun2:%d\n”,n);
return 2;
}
int main(void)
{
int (*fp)(int); //函数指针
fp = fun1;
fp = &fun1;
fp = *fun1;
//fun(100);
fp(200);
(*fp)(200);
printf(“fun1:%p\n”,fun1);
printf(“fun1:%p\n”,*fun1);
printf(“&fun1:%p\n”,fp);
printf(“fun1:%p\n”,fun1+1);
printf(“fun1:%p\n”,*fun1+1);
printf(“&fun1:%p\n”,fp+1);
return 0;
}
max.c
#include<stdio.h>
struct employee
{
char name[20];
int age;
float salary;
}Employee;
typedef struct employee Employee
Employee *getMax(Employee emps[],int len,int (*comp)(Employee *,Employee *))
{
int i;
Employee *max_emp = emps;
for(i =0;i<len;i++)
{
if(comp(emps+i,max_emp)>0)
max_emp = emps+i;
}
return max_emp;
}
void out_emp(Employee *e)
{
printf(“—-Employee info——-\n”);
printf(“Name:%s “e->name);
printf(“Age:%d “e->age);
printf(“Salary:%.2f “e->salary);
printf(“\n”);
}
int comp_name(Employee *e1,Employee *e2)
{
return strcmp(e1->name,e2->name);
}
int comp_age(Employee *e1,Employee *e2)
{
return e1->age – e2->age;
}
int comp_salary(Employee *e1,Employee *e2)
{
if(e1->salary – e2->salary > 0)
return 1;
else
return -1;
}
int main(void)
{
Employee emps[] =
{
{“Zhangsan”,22,23232.2},
{“Lisi”,11,890098.3},
{“Wangwu”,44,5465.5}
};
int len = sizeof(emps)/sizeof(emps[0]);
out_emp(getMax(emps,len,comp_name));
return 0;
}