指针函数与函数指针
指针函数:->int*p();
函数指针:->int (*p)();
定义char 类型的指针,返回字符串:
指针函数:使用指针作为返回值的函数
//指针函数 #include<iostream> char *getchar(char); char *getchar(char c){ switch(c){ case 'A':return "apple"; case 'B' :return "banana"; case 'C': return "Cat"; case 'D': return "Dog"; default: return "Nome"; } } int main(){ char input; printf("请输入一个字母"); scanf("%c",&input); printf("%s\n",getchar(input)) ; return 0; }
函数指针;
//指针函数 #include<iostream> int square(int num){ return num*num; } int main(){ int num; int (*fp)(int); printf("请输入一个整数:"); scanf("%d",&num); fp=square; printf("%d*%d=%d ",num,num,(*fp)(num));
printf("%d*%d=%d ",num,num,fp(num));//fp相当于函数名
return 0; }
函数指针作为参数:
//函数指针作为参数: #include<iostream> int add(int num1,int num2){ return num1+num2; } int sub(int num1,int num2){ return num1-num2; } int calc(int (*fp)(int,int),int num1,int num2){ return (*fp)(num1,num2); } int main(){ printf("3+5=%d\n",calc(add,3,5)); printf("3-5=%d\n",calc(sub,3,5)); return 0; }
将函数指针作为返回值
#include <stdio.h> int add(int, int); int sub(int, int); int calc(int (*)(int, int), int, int); int (*select(char))(int, int); int add(int num1, int num2) { return num1 + num2; } int sub(int num1, int num2) { return num1 - num2; } int calc(int (*fp)(int, int), int num1, int num2) { return (*fp)(num1, num2); } int (*select(char op))(int, int) { switch(op) { case '+': return add; case '-': return sub; } } int main() { int num1, num2; char op; int (*fp)(int, int); printf("输入一个式子(3-2)"); scanf("%d%c%d", &num1, &op, &num2); fp = select(op); printf("%d %c %d = %d\n", num1, op, num2, calc(fp, num1, num2)); return 0; }