指针函数与函数指针
O、指针

一、函数指针
1.定义:是一个指针,类似其他数据类型的指针(但指向函数的指针变量没有 ++ 和 -- 运算。),该指针指向的是一个函数,也可以认为指向的是函数的入口地址
2.用法:先定义一个普通函数(当然也包括指针函数),再定义一个指针,赋值时函数不带括号也不带参数(有两种赋值方法),指向该函数,最后再调用
3.优点
4.适用:
二、指针函数
1.定义:是一个函数,而这个函数的返回值是一个指针
2.用法:先定义一个指针函数,再定义一个指针,类型为函数返回类型
3.优点:
三、简单代码:
1 #include <iostream> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 6 using namespace std; 7 int swap1 (int p1,int p2)//函数指针的话首先要定义一个普通函数 8 { 9 if(p1>p2) 10 return p1; 11 else { 12 return p2; 13 } 14 } 15 int *swap2(int p1, int p2) //指针函数的话,就是普通函数加个*,表示返回的是个指针,即地址(可以类似考虑整形指针,字符指针等) 16 { 17 int *p = (int *)malloc(sizeof(int)); 18 ///int *p;//这样是申请不到内存的,用的时候会出错的 19 printf("2The memeory address of p = 0x%x \n", p); 20 memset(p, 0, sizeof(int));//表示把p的位置用0填充sizeof(int)个字节 21 if(p1>p2) 22 *p=p1; 23 else { 24 *p=p2; 25 } 26 printf("*p = %d \n", *p); 27 printf("*p1 = %d \n", p1); 28 return p; 29 ///return &p1;//是错的,返回的只能是一个指针不能是一个地址 30 } 31 32 int (*fun1)(int x,int y);//再定义一个函数指针,该函数指针的形式和函数一致 33 34 35 int main()//调用 36 { 37 int c=3;int d=4; 38 std::cout << "(c,d) = " << c << d << std::endl; 39 40 fun1 = swap1;//第一种写法:函数名即指向函数的入口地址,编译器在编译的时候会指向这个入口地址, 41 (*fun1)(c,d); 42 std::cout << "(*fun1)(c,d) = " << (*fun1)(c,d) << std::endl; 43 44 fun1 = &swap1;//又有两种写法,取函数所在的地址 45 std::cout << "(*fun1)(c,d) = " << fun1(c,d) << std::endl; 46 47 //调用指针函数 48 // int *p0;//此时是未给p分配内存空间的,用的时候会出错的 49 // printf("1The memeory address of p = 0x%x \n", p0); 50 int *p=&c;// 51 printf("2The memeory address of p = 0x%x \n", p); 52 53 p=swap2(c,d);//调用指针函数,函数的返回值是一个指针 54 std::cout << "(*fun1)(c,d) = " << *p<< std::endl; 55 }
四、综合了函数指针和指针函数的代码
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 char* fun(char* p1,char* p2)//定义了一个指针函数 6 7 { 8 int i = 0; 9 i = strcmp(p1,p2); 10 if(0 != i) 11 { 12 printf("*p = %d \n", *p1); 13 return p1; 14 } 15 16 else 17 { 18 printf("*p = %d \n", *p2); 19 return p2; 20 } 21 22 } 23 24 int main() 25 { 26 char * (*pf)(char* p1,char* p2); 27 pf = &fun; 28 (*pf)("a","b"); 29 return 0; 30 }
浙公网安备 33010602011771号