首页 > 代码库 > 指针函数和函数指针

指针函数和函数指针

指针函数

//指针函数#include"stdio.h"char *arr[]={"AAA","BBB","CCC"};//数组里面装字符串的时候只能用指针的形式,里面装的是各个字符串的地址char *fun(int n);main(){ int i=0; for(i=0;i<3;i++) {    printf("%s\n",fun(i)); }}char *fun(int n){return (arr[n]);}

函数指针

//函数指针#include"stdio.h"unsigned char AAA(void);     //声明函数AAAunsigned char BBB(void);     //声明函数BBBunsigned char CCC(void);     //声明函数CCCtypedef unsigned char (*pFun)(void); //定义函数指针pFun 注意:这里面必须得用typedef来定义pFun,其实相当于定义了一种新的类型类似于int.pFun arr[]={AAA,BBB,CCC};main(){       int i=0;    unsigned char output=x;    for(i=0;i<3;i++)    {    output=(arr[i])();    printf("%c\n",output);    }}unsigned char AAA(void){return A;}unsigned char BBB(void){return B;}unsigned char CCC(void){return C;}

指针函数和函数指针相结合

//函数指针和指针函数相结合#include"stdio.h"unsigned char AAA(void);     //声明函数AAAunsigned char BBB(void);     //声明函数BBBunsigned char CCC(void);     //声明函数CCCtypedef unsigned char fun(void);  //自定义fun类型fun *arr[]={AAA,BBB,CCC};         //如果上面不自定fun类型,arr的类型将无法准确定义,假设你定义成unsigned char虽然没有error,但是也会有warningmain(){    int i=0;    unsigned char output;    for(i=0;i<3;i++)    {//    output=((unsigned char(*)(int))arr[i])(0);    output=((unsigned char(*)(void))arr[i])();//根据函数的地址来调用函数的两种方式    printf("%c\n",output);    }}unsigned char AAA(void){return A;}unsigned char BBB(void){return B;}unsigned char CCC(void){return C;}

 

指针函数和函数指针