指向函数的指针、typedef、奇特的声明

来源:互联网 发布:xp自动修复软件 编辑:程序博客网 时间:2024/05/02 16:18


1 指向函数的指针

函数名、函数参数、函数的返回类型唯一决定了一个函数。

函数参数、函数的返回类型则决定了一类函数。

指向函数的指针是具有类型的,这个类型就是函数的类型:函数参数和函数的返回类型一样的那一类函数。

指向函数的指针变量一般定义为:


返回类型 (*指针变量名) (函数参数列表)


若用typedef,这样定义:

typedef 返回类型 (*指针变量名) (函数参数列表)

此时可以用"指针变量名"来定义指向特定类型的函数的指针变量了。


(1)例子1

函数原型:

void display(int *);

声明指向这种类型(具有int *类型的函数参数,具有void的返回类型)的函数的指针:

void (* pf) (int *);  //声明指向函数的指针变量pf


下面是利用pf调用display函数的代码:

int a = 5;void (*pf)(int *); //声明指向display这种类型函数的指针pf = display;      //把display函数的地址赋给pf(*pf)(&a);         //调用pf指向的函数

(2) 例子2
函数原型:

int func1(char *, int);int func2(void);

声明指向函数的指针:

int (*pf)(char *, int); //声明指向func1类型的函数的指针int (*pf2)(void);       //或int (*pf2)(), 声明指向func2类型的函数的指针


(3) 例子3

函数原型:

int * func3(int);

声明指向函数的指针:

int * (*pf3)(int);     //(int *) (*pf)(int)是错误的

2 typedef

它和#define指令类似,但是两者有三个不同之处:

(1) 与#define不同,typedef给出的符号名称仅限于对类型,而不是对值;

(2) typedef的解释由编译器执行,而#define是由预处理器执行;

(3) 范围比#define更有限,但在受限范围内,typedef更灵活;

如:

typedef unsigned char byte;

之后就可以用byte代替 unsigned char 声明变量了。


3. 一些奇特的声明

摘自<C Primer Plus>

int board[8][8];     // an array of arrays of intint ** ptr;          // a pointer to a pointer to intint * risks[10];     // a 10-element array of pointers to intint (* rusks)[10];   // a pointer to an array of 10 intsint * oof[3][4];     // a 3 x 4 array of pointers to intint (* uuf)[3][4];   // a pointer to a 3 x 4 array of intsint (* uof[3])[4];   // a 3-element array of pointers to 4-element arrays of int

char (* flump[3])(); // array of 3 pointers to functions that                     //return type char                     //有三个指针组成的数组,每个指针指向返回类型为char的函数