c語言——函式指標
函式具有可賦值給指標的實體記憶體地址,一個函式的函式名就是一個指標,它指向函式的程式碼。一個函式的地址是該函式的進入點,也是呼叫函式的地址。函式的呼叫可以通過函式名,也可以通過指向函式的指標來呼叫。函式指標還允許將函式作為變元傳遞給其他函式。
不帶括號和變數列表的函式名,這可以表示函式的地址,正如不帶下標的陣列名可以表示陣列的首地址。
定義形式:
型別 (*指標變數名)(引數列表);
例如:
int (*p)(int i,int j);
p是一個指標,它指向一個函式,該函式有2個整形引數,返回型別為int。p首先和*結合,表明p是一個指標。然後再與()結合,表明它指向的是一個函式。指向函式的指標也稱為函式指標。
例1:
-
#include <stdio.h>
-
#define GET_MAX 0
-
#define GET_MIN 1
-
int get_max(int i,int j)
-
{
-
return i>j?i:j;
-
}
-
int get_min(int i,int j)
-
{
-
return i>j?j:i;
-
}
-
int compare(int i,int j,int flag)
-
{
-
int ret;
-
//這裡定義了一個函式指標,就可以根據傳入的flag,靈活地決定其是指向求大數或求小數的函式
-
//便於方便靈活地呼叫各類函式
-
int (*p)(int,int);
-
if(flag == GET_MAX)
-
p = get_max;
-
else
-
p = get_min;
-
ret = p(i,j);
-
return ret;
-
}
-
int main()
-
{
-
int i = 5,j = 10,ret;
-
ret = compare(i,j,GET_MAX);
-
printf("The MAX is %d\n",ret);
-
ret = compare(i,j,GET_MIN);
-
printf("The MIN is %d\n",ret);
-
return 0 ;
-
}
例2:
-
#include <stdio.h>
-
#include <string.h>
-
void check(char *a,char *b,int (*cmp)(const char *,const char *));
-
main()
-
{
-
char s1[80],s2[80];
-
int (*p)(const char *,const char *);
-
//將庫函式strcmp的地址賦值給函式指標p
-
p=strcmp;
-
printf("Enter two strings.\n");
-
gets(s1);
-
gets(s2);
-
check(s1,s2,p);
-
}
-
void check(char *a,char *b,int (*cmp)(const char *,const char *))
-
{
-
printf("Testing for equality.\n");
-
//表示式(*cmp)(a,b)呼叫strcmp,由cmp指向庫函式strcmp(),由a和b作呼叫strcmp()的引數。
-
//呼叫時,與宣告的情況類似,必須在*cmp周圍使用一對括號,使編譯程式正確操作,
-
//同時這也是一種良好的編碼風格,指示函式是通過指標呼叫的,而不是函式名。
-
if((*cmp)(a,b)==0)
-
printf("Equal\n");
-
else
-
printf("Not Equal\n");
-
}
例3:
-
#include <stdio.h>
-
#include <ctype.h>
-
#include <stdlib.h>
-
#include <string.h>
-
//check()函式的第3個函式是函式指標,就可以根據具體情況傳入不同的處理函式
-
void check(char *a,char *b,int (*cmp)(const char *,const char *));
-
//自定義的比較兩個字串的函式
-
int compvalues(const char *a,const char *b);
-
main()
-
{
-
char s1[80],s2[80];
-
printf("Enter two values or two strings.\n");
-
gets(s1);
-
gets(s2);
-
//如果是數字,則用函式指標傳入數字比較函式進行處理
-
if(isdigit(*s1)){
-
printf("Testing values for equality.\n");
-
check(s1,s2,compvalues);
-
}
-
//如果是字串,則用函式指標傳入庫函式strcmp進行處理
-
else{
-
printf("Testing strings for equality.\n");
-
check(s1,s2,strcmp);
-
}
-
}
-
void check(char *a,char *b,int (*cmp)(const char *,const char *))
-
{
-
if((*cmp)(a,b)==0)
-
printf("Equal.\n");
-
else
-
printf("Not Equal.\n");
-
}
-
int compvalues(const char *a,const char *b)
-
{
-
if(atoi(a)==atoi(b))
-
return 0;
-
else
-
return 1;
-
}
注意:
int *f(int i, int j);
int (*p)(int i, int j);
前者是返回值是指標的函式;後者是一個指向函式的指標。