1.指向函数的指针
用函数指针变量调用函数
#include<stdio.h>
main()
{
int max(int x,int y);
int (*p)();//函数指针变量
int a,b,c;
p=max;
scanf("%d %d",&a,&b);
c=(*p)(a,b);//函数指针变量调用函数
printf("a=%d,b=%d,max=%d",a,b,c);
}
int max(int x ,int y)
{
int z;
if(x>y) z=x;
else z=y;
return z;
}
start without debugging
2.指向函数的指针做函数参数
max min add
#include<stdio.h>
main()
{
int max(int x,int y);
int min(int x,int y);
int add(int x,int y);
void process1(int x,int y,int(*fun)());
int a,b;
puts("enter a and b");
scanf("%d %d",&a,&b);
puts("max");
process1(a,b,max);
puts("min");
process1(a,b,min);
puts("add");
process1(a,b,add);
}
void process1(int x,int y,int(*fun)())
{
printf("%d",(*fun)(x,y));
}
int max(int x ,int y)
{
int z;
if(x>y) z=x;
else z=y;
return z;
}
int min(int x ,int y)
{
int z;
if(x<y) z=x;
else z=y;
return z;
}
int add(int x ,int y)
{
int z;
z=x+y;
return z;
}
start without debugging
3.返回指针值的函数
输出指定学生的4科成绩
#include<stdio.h>
main()
{
double score[][4]={{23.45,87.88,13.87,23.00},{83.40,87.84,19.87,93.00}};
double *search(double(*pointer)[4],int n);
double *p;
int i,m;
puts("please enter the number of student");
scanf("%d",&m);m--;
p=search(score,m);
for(i=0;i<4;i++) printf("%5.2f\t",*(p+i));//%5.2:左对齐,总长度取5位,保留两位小数
}
double *search(double(*pointer)[4],int n)
{
double *pt;
pt=*(pointer+n);
return pt;
}
start without debugging
#include<stdio.h>
main()
{
double score[][4]={{23.45,87.88,13.87,23.00},{83.40,87.84,19.87,93.00}};
double *search(double(*pointer)[4],int n);
double *p;
int i,m;
puts("please enter the number of student");
scanf("%d",&m);m--;
p=search(score,m);
for(i=0;i<4;i++) {
if (*(p+i)<60)
printf("不及格:%5.2f\t",*(p+i));
else
printf("及格:%5.2f\t",*(p+i));
}
}
double *search(double(*pointer)[4],int n)
{
double *pt;
pt=*(pointer+n);
return pt;
}