一.什么是函數指針:
函數指針本質上也是指針,我們所寫函數代碼在內存中會被分配一段專門的儲存空間,這段儲存空間的地址就是函數的地址,既然是地址,就可以用指針去表示,自然就有了函數指針。
二.函數指針的用法:
1.首先明確函數指針怎么申明。形如:返回值類型 (*變量名)(參數類型1,參數類型2,。。。)
例如
int (*p) (int,int)
2.我們還需要了解如何通過指針調用函數。
(*p)(3,5);
3.如何給該類型的指針賦值:
非常簡單,直接將函數名賦給指針即可,因為函數名即為函數的首地址,這樣的賦值順理成章。
例如:
int Func(int x); /*聲明一個函數*/ int (*p) (int x); /*定義一個函數指針*/ p = Func; /*將Func函數的首地址賦給指針變量p*/
4.請看一下完整的用法:
# include <stdio.h> int Max(int, int); int main(void) { int(*p)(int, int); int a, b, c; p = Max; printf("please enter a and b:"); scanf("%d%d", &a, &b); c = (*p)(a, b); //通過函數指針調用Max函數 printf("a = %d\nb = %d\nmax = %d\n", a, b, c); return 0; } int Max(int x, int y) { int z; if (x > y) { z = x; } else { z = y; } return z; }
5.特別注意:
請一定要分清楚指針函數和函數指針的區別。指針函數是指一個函數的返回值類型為指針。下面請看一段代碼來了解指針函數:
#include <stdio.h> #include <stdlib.h> #include <string.h> char *InitMemory() //指針函數 { char *s = (char *)malloc(sizeof(char) * 32); return s; } int main() { char *ptr = InitMemory(); strcpy(ptr, "helloworld"); printf("%s\n", ptr); free(ptr); return 0; }
