星期四, 3月 23, 2017

[ C ] Function Pointer 用法



function pointer簡單說就是function的指標,
先從一個最簡單的function說起,

int addInt(int n, int m) {
return n+m;
}

一般會直接呼叫addInt(2,3)來使用function,
而function pointer是宣告一個和addInt一樣型態的function pointer,

int (*call)(int, int);

不管是回傳值和參數都要一樣,
要使用時有兩種方式,

第一種是把function的位址丟給它,

call = &addInt;

並利用(*)的方式來拿取回傳值/呼叫function。

int sum = (*call)(2, 3);

第二種是你可以不要使用&的方式,
然後也不要使用*,這樣程式一樣可以執行。

call = addInt;
sum = call(4, 5);

SourceCode

之後要說的是第二種型態的function pointer,
是利用call function時就直接傳function name去給他,

void redirect_func(int (*call_this)(int, int))
{
printf("3*4=[%d]\n", call_this(3, 4));
}

redirect_func(do_multiply);

我呼叫redirect_func並且傳"do_multiply"的function name,
而redirect_function內的參數型態是function pointer,
所以他代表的意思像是,

call_this = do_multiply;

然後redirect_function內是呼叫call_this這參數來做動作,
所以等於是呼叫do_multiply function。

*另一種宣告參數方式

typedef int (*call_def)(int, int);

我直接宣告 call_def 是function pointer的型態,

call_def call_this

用這樣的方式就等於是

int (*call)(int, int);
call = call_this

然後在function內當參數時就可以少打一些字,

void type_redirect_func(call_def call_this){}

之後使用方法就像上面例子一樣。

SourceCode

如果利用array方式來存function pointer ???

一開始那些function的型態需要是一樣(參數及回傳值),

int (*call[])(int, int) = {add, mult, sub};

然後用array的方式來存那些function name,
要使用的話就利用array的存取方式來用,

(*call[i])(2,1)

當然不用*也可以,

call[i](2,1)

i值是來看要使用第幾個function name。

SourceCode

Note:
1. 不像一般的pointer,function pointer是指向code而不是data。
2. function pointer不需要allocate / de-allocate 空間。


Ref

沒有留言: