函数指针:
是指返回的变量的类型是指针类型
?
#include<stdio.h>
char*getWord(char c)
{
char str1[]="apple";
char str2[]="banana";
char str3[]="cat";
switch(c)
{
case'A':return str1;
case'B':return str2;
case'C':return str3;
}
}
int main()
{
char input;
printf("please input a char:\n");
input=getchar();
printf("input is %c\n",input);
printf("geetWord is %s\n",getWord(input));
getchar();
return 0;//不要返回局部变量的指针,他会被释放
}
?
这种情况下的geetword打印的结果什么都没有,因为apple被存在一个局部变量里面,这个局部变量只在 一个函数周期内有效,当geetword函数结束时,str1就会被释放,所以打印结果为空
?
#include<stdio.h>
char*getWord(char c)
{
switch(c)
{
case'A':return "apple";
case'B':return "banana";
case'C':return "cat";
}
}
int main()
{
char input;
printf("please input a char:\n");
input=getchar();
printf("input is %c\n",input);
printf("geetWord is %s\n",getWord(input));
return 0;//这样的设置apple就是字符串常量,是在整个函数运行之后再被释放
}
?
字符常量就可以
指针函数
这个通常是指你已经有几个设置好的函数,然后你在用的时候,并没有想好,就把那个函数的名字那里设置了一个指针类型,之后你想用那个就用那个
?
#include<stdio.h>
int square(int num)
{
return num*num;
}
int main()
{
int num;
int(*p)(int);//函数名字还没有确定,就先设置一个指针,函数需要一个int数据
printf("please input a number:\n");
scanf("%d",&num);
p=square;//这个应该是给函数的首地址
printf("p=%x ,%d\n",p,(*p)(num));
return 0;
}
?
可以注意一下这两个的表达形式:
函数指针:int*arr(int a1,int a2);
指针函数:int(*p)(int,int);
?
#include<stdio.h>
int add(int num1,int num2)
{
return num1+num2;
}
int sub(int num1,int num2)
{
return num1-num2;
}
int main()
{
int num1;
int num2;
scanf("%d %d",&num1,&num2);
int(*p)(int,int);
p=add;
printf("result is %d\n",(*p)(num1,num2));
return 0;
}
?
#include<stdio.h>
double function1(double num1,double num2)
{
return num1+num2;
}
double function2(double num1,double num2)
{
return num1-num2;
}
double function3(double num1,double num2)
{
return num1*num2;
}
double function4(double num1,double num2)
{
return num1/num2;
}
int main()
{
double (*f[4]) (double,double)={function1,function2,function3,function4};
double num1,num2;
printf("please input a number between 0,1,2,3\n");
int function;
scanf("%d",&function);
while(function>=0&&function<=3)
{
printf("please enter two figures:\n");
scanf("%lf %lf",&num1,&num2);
double result=(*f[function])(num1,num2);
printf("the result is %f\n",result);
printf("再来\n");
printf("please input a number between 0,1,2,3\n");
scanf("%d",&function);
}
return 0;
}
?
#include<stdio.h>
int add(int num1,int num2)
{
return num1+num2;
}
int sub(int num1,int num2)
{
return num1-num2;
}
int calculate(int(*p)(int,int),int num1,int num2)
{
return (*p)(num1,num2);
}
int main()
{
int num1;
int num2;
scanf("%d %d",&num1,&num2);
int(*p)(int,int);
p=add;
printf("result is %d\n",(*p)(num1,num2));
printf("another result is %d\n",calculate(sub,10,23));
printf("ananother result is %d\n",calculate(add,34,54));
return 0;
}
?