2010年5月24日 星期一

函式指標的用法

函式指標的應用,可減少判斷的次數;把函式當成參數傳遞。此處轉貼一個學c的連結:C程式語言教學
方法一:
ulong FUNC(ulong param1, ulong param2, ulong param3){
........
........
return retval;
}
void Call_FUNC(int paramX, void* paramY){
........
........
return;
}
void Main_FUNC(){
........
Call_FUNC( x , (void*)FUNC);
........
return;
}
方法二:
struct STRUCTNAME{
int A;
unsigned B;
char *NAME;
long (*FUNC_X)(void);
void (*FUNC_Y)(int,long);
};
static long ptr1_func(void){
......
}
static void ptr2_func(int i, long k){
......
}
static long ptr3_func(void){
......
}
static void ptr4_func(int a, long b){
......
}
static long ptr5_func(void){
......
}
static void ptr6_func(int v, long u){
......
}
static long ptr7_func(void){
......
}
static void ptr8_func(int n, long f){
......
}
static struct STRUCTNAME struct_array[] = {
{ x, x , "xxxx", ptr1_func , ptr2_func(x,y)},
{ x, x , "xxxx", ptr3_func , ptr4_func(d,e)},
{ x, x , "xxxx", ptr5_func , ptr6_func(f,g)},
{ x, x , "xxxx", ptr7_func , ptr2_func(j,k)},
{ x, x , "xxxx", ptr3_func , ptr8_func(r,t)}
};
函式指標呼叫如下
struct_array[index].FUNC_X();
struct_array[index].FUNC_Y(intN,longM);
以下轉貼自程式設計俱樂部http://www.programmer-club.com.tw/ShowSameTitleN/c/33283.html

最近在trace code看到一個函式指標的觀念想請教一下,我寫了一個範例code如下
#include
#include
int fun(int, int);
typedef int(*fun_one)(int, int); //書上大部分介紹函式指標的寫法
typedef int(fun_two)(int, int); //這是在trace linux kernel code看到的寫法
int test1(fun_one);
int test2(fun_two *);
int main(void){
test1(fun);

test2(fun);

return 0;
}

int fun(int x, int y){
printf("x : %d, y : %d\n", x, y);
}
int test1(fun_one f1)//這邊不用多加一個指標(*)的符號
{f1(1,1);}
int test2(fun_two *f2)//要宣告f2是指向fun_two的指標
{f2(2,2);}
這邊兩種方式都可以run。
--> 閱讀更多...