Linux C 编程教程第 25 部分 - 函数指针
在此页
- C 编程语言中的函数指针
- 结论
到目前为止,在这个正在进行的 C 编程教程系列中,我们已经讨论了指针的基本概念以及与指针相关的许多方面,例如指向数组的指针和指针数组。扩展我们对指针的理解,在本教程中,我们将讨论函数指针的概念。
C语言中的函数指针
就像我们有指向变量的指针一样,也可以有指向函数的指针。以下是函数指针声明的示例:
void (*fn_ptr)(int)
所以这里我们有一个名为 fn_ptr 的函数指针,它可以指向任何返回 void 并接受整数作为输入的函数。不用说,这只是声明部分 - 与任何其他指针一样,您需要为其分配一个地址(在本例中为函数的地址)才能使用它。
以下是使用此指针的示例:
#include <stdio.h>
void print_int(int a)
{
printf("\n The integer value is: %d\n",a);
}
int main()
{
void (*fn_ptr)(int);
fn_ptr = &print_int;
(*fn_ptr)(10);
return 0;
}
如您所见,我们首先定义了一个函数 print_int,它接受一个整数并返回 void。然后,在 main 函数中,我们将 fn_ptr 声明为函数指针,可以指向像 print_int 这样的函数。随后将 print_int 函数的地址分配给 fn_ptr,最后使用指针调用该函数。
这是产生的输出:
The integer value is: 10
这里值得一提的是,您可以通过避免最后两行中的 & 和 * 来进一步简化该程序。以下是修改后的代码:
#include <stdio.h>
void print_int(int a)
{
printf("\n The integer value is: %d\n",a);
}
int main()
{
void (*fn_ptr)(int);
fn_ptr = print_int;
fn_ptr(10);
return 0;
}
继续,就像指针数组一样,您也可以拥有函数指针数组。例如,下面是一个函数指针数组,可以存储 3 个函数地址。
void (*fn_ptr[3])(int)
下面是一个使用这个指针数组的例子:
void print_int1(int a)
{
printf("\n The integer value is: %d\n",a);
}
void print_int2(int a)
{
printf("\n The integer value is: %d\n",a+1);
}
void print_int3(int a)
{
printf("\n The integer value is: %d\n",a+2);
}
int main()
{
void (*fn_ptr[3])(int);
fn_ptr[0] = print_int1;
fn_ptr[1] = print_int2;
fn_ptr[2] = print_int3;
fn_ptr[0](10);
fn_ptr[1](10);
fn_ptr[2](10);
return 0;
}
这是此代码产生的输出:
The integer value is: 10
The integer value is: 11
The integer value is: 12
您应该了解的函数指针的另一个方面是您也可以将它们用作函数参数。例如,可以有一个函数接受指向函数的指针作为参数。例如:
void some_random_func(void (*fn_ptr)(int))
以下是使用此功能的示例代码:
#include <stdio.h>
void another_random_func(int a)
{
printf("\n The integer to entered is: %d\n", a);
}
void some_random_func(void (*fn_ptr)(int))
{
fn_ptr(5);
}
int main()
{
some_random_func(another_random_func);
return 0;
}
所以我们在这里所做的是,我们创建了一个名为 some_random_func 的函数,它在输入中接受一个函数指针。然后,从 main 开始,我们调用了 some_random_func ,并将另一个函数 another_random_func 的地址作为参数。然后使用指针,我们成功调用了another_random_func。
继承人的输出:
The integer to entered is: 5
结论
当您想创建称为回调机制的东西时,函数指针可以派上用场(在此处阅读更多相关信息)。但在开始之前,最好能很好地理解这个概念。我们建议您在本地计算机上尝试本教程中的示例(并创建新示例)。如有任何疑问或疑问,请在下方发表评论。