9月 08, 2009

函數指標(Function pointer example)

Keyword:Function pointer, Callback function

程式在執行時,函式在記憶體中會有一個位置。函式名稱,其實就是指向該位置。同理仿照,可以建立一函式指標(Function pointer)指向該函式,宣告方式如下:
傳回值型態 (*指標名稱)(傳入參數);

int (*FP)(); /* FP 指向的函式傳入void,回傳int。 */
實際使用狀況如下,透過 FP 函式指標來呼叫 foo()
#include <stdio.h>
void foo()
{
printf ("Hello World!!");
}

int main()
{
void (*FP)(); /* void (*FP)() = foo; */
FP = foo ;
(*FP)(); /* same as using FP(); */
return 0;
}

沒有留言:

張貼留言