如何使用 C 程式為函式分配一個指標?
指向函式的指標
它儲存記憶體中函式定義的基礎地址。
宣告
datatype (*pointername) ();
函式名稱本身指定函式的基礎地址。因此,使用函式名稱初始化。
例如,
int (*p) (); p = display; //display () is a function that is defined.
示例 1
我們將看到一個使用指向函式的指標呼叫函式的程式 -
#include<stdio.h> main (){ int (*p) (); //declaring pointer to function clrscr (); p = display; *(p) (); //calling pointer to function getch (); } display (){ //called function present at pointer location printf(“Hello”); }
輸出
Hello
示例 2
讓我們考慮另一個解釋指向函式指標概念的程式 -
#include <stdio.h> void show(int* p){ (*p)++; // add 1 to *p } int main(){ int* ptr, a = 20; ptr = &a; show(ptr); printf("%d", *ptr); // 21 return 0; }
輸出
21
廣告