C語言中指標函式與函式指標有何區別

指標函式和函式指標是C語言入門學習中的基礎知識,以下是本站小編搜尋整理的關於C語言中指標函式與函式指標的區別,有需要的朋友可以參考一下!想了解更多相關資訊請持續關注我們應屆畢業生考試網!

C語言中指標函式與函式指標有何區別

指標函式一般是指返回指標的函式;

#include <stdio.h>

int* fun(int *a)

{

return a;

}

int main(int argc, char **argv)

{

int a = 3;

printf("%d", *(fun(&a)));

return 0;

}

函式指標是表示指向函式開始地址的指標:

首先要了解函式的呼叫過程:

#include <stdio.h>

int fun(int i)

{

return i + 1;

}

int main(int argc, char **argv)

{

int r;

//r = fun(5);

r = (*fun)(5); //呼叫方式

printf("%d ", r);

return 0;

}

函式可以用r = (*fun)(5);來呼叫,說明函式名其實是一個指標,

通過(*fun)來定址。所以我們就可以定義一個指標

#include <stdio.h>

int fun(int i)

{

return i + 1;

}

int main(int argc, char **argv)

{

int r;

int (*funP)(int); //宣告指標

//funP = fun; //給指標賦值

funP = &fun;

r = funP(5);

printf("%d ", r);

return 0;

}

所以,給函式指標賦值也有兩種方式;

同樣,通過函式指標呼叫函式的方式也有兩種:

#include <stdio.h>

int fun(int i)

{

return i + 1;

}

int main(int argc, char **argv)

{

int r;

int (*funP)(int); //宣告指標

funP = fun; //給指標賦值

//r = funP(5);

r = (*funP)(5); //呼叫

printf("%d ", r);

return 0;

}

也就是說,除了宣告的地方,fun()與(*fun)()的`作用是一樣的。

這樣,也就讓C語言容易實現類似於回撥函式的結構:

#include <stdio.h>

int funA(int i)

{

return i + 1;

}

int funB(int i)

{

return i - 1;

}

void fun(int (*funP)(int), int i)

{

printf("%d ", funP(i));

}

int main(int argc, char **argv)

{

int (*funP)(int); //宣告指標

funP = funA; //給指標賦值

//funP = funB; //給指標賦值

fun(funP, 5); //呼叫

return 0;

}

在fun()函式裡,它做的只是在某個時候呼叫一個funP指標指向的函式,至於是哪個函式,在fun函式的定義處還無從得知;直到將funA賦給函式指標funP,funP具體要做什麼功能,才得以確定。

也就是說,main函式決定fun函式需要幫它實現什麼函式程式碼,但是fun何時呼叫以及是否呼叫main給他的函式,那是由fun()來決定。