如何使用 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

更新日期: 09-Mar-2021

684 次浏览

开启你的 职业生涯

完成课程认证

开始学习
广告
© . All rights reserved.