# 函數指針
函數指針是指向函數的指針變量。
函數指針可以像一般函數一樣,用于調用函數、傳遞參數。
## 聲明
```
typedef int (*fun_ptr)(int,int); // 聲明一個指向同樣參數、返回值的函數指針類型
```
## 舉個栗子
```
#include <stdio.h>
int max(int x, int y)
{
return x > y ? x : y;
}
int main(void)
{
/* p 是函數指針 */
int (* p)(int, int) = & max; // &可以省略
int a, b, c, d;
printf("請輸入三個數字:");
scanf("%d %d %d", & a, & b, & c);
/* 與直接調用函數等價,d = max(max(a, b), c) */
d = p(p(a, b), c);
printf("最大的數字是: %d\n", d);
return 0;
}
打印結果:
請輸入三個數字:1 2 3
最大的數字是: 3
```
# 回調函數
## 含義
函數指針變量可以作為某個函數的參數來使用的,回調函數就是一個通過函數指針調用的函數。
?? 簡單講:回調函數是由別人的函數執行時調用你實現的函數。
```
你到一個商店買東西,剛好你要的東西沒有貨,于是你在店員那里留下了你的電話,過了幾天店里有貨了,店員就打了你的電話,然后你接到電話后就到店里去取了貨。在這個例子里,你的電話號碼就叫回調函數,你把電話留給店員就叫登記回調函數,店里后來有貨了叫做觸發了回調關聯的事件,店員給你打電話叫做調用回調函數,你到店里去取貨叫做響應回調事件。
```
> YJ:類似 OC 中的 Block
## 舉個栗子(不夠形象,重新找栗子)
```
#include <stdlib.h>
#include <stdio.h>
// 回調函數 getNextValue
void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
for (size_t i=0; i<arraySize; i++)
array[i] = getNextValue();
}
// 獲取隨機值
int getNextRandomValue(void)
{
return rand();
}
int main(void)
{
int myarray[10];
populate_array(myarray, 10, getNextRandomValue);
for(int i = 0; i < 10; i++) {
printf("%d ", myarray[i]);
}
printf("\n");
return 0;
}
打印結果:
16807 282475249 1622650073 984943658 1144108930 470211272 101027544 1457850878 1458777923 2007237709
```
> size_t 是一種數據類型,近似于無符號整型,但容量范圍一般大于 int 和 unsigned。這里使用 size_t 是為了保證 arraysize 變量能夠有足夠大的容量來儲存可能大的數組。