本文解释了如何在 C 语言中声明指向变量、数组和结构体的指针。除此之外,还可以定义指向函数的指针。这个特性使得函数能够作为参数传递给其他函数。例如,这在构建一个用于确定多种数学函数解的函数时非常有用。

声明函数指针的语法相对复杂,因此我们从一个简化的例子开始:声明一个指向标准库函数 printf() 的指针:

/* ptrprt.c */
#include <stdio.h>

void main()
{
    int (*func_ptr) ();                  /* 声明指针 */
    func_ptr = printf;                   /* 将函数赋给指针 */
    (*func_ptr) ( "Printf is here!\n" ); /* 执行函数 */
}

函数指针必须声明为与它所表示的函数相同的类型(在本例中是 int 类型)。

接下来,我们将函数指针传递给另一个函数。该函数假定传递给它的函数是接受 double 类型参数并返回 double 类型值的数学函数:

/* ptrroot.c */
#include <stdio.h>
#include <math.h>

void testfunc ( char *name, double (*func_ptr) () );

void main()
{
    testfunc( "square root", sqrt );
}

void testfunc ( char *name, double (*func_ptr) () )
{
    double x, xinc;
    int c;

    printf( "Testing function %s:\n\n", name );
    for( c=0; c < 20; ++c )
    {
        printf( "%d: %f\n", c, (*func_ptr)( (double)c ) );
    }
}

显然,并不是所有的函数都能传递给 testfunc()。传递给该函数的函数必须与期望的参数数量、类型,以及返回值类型一致。

Last modified: Tuesday, 28 January 2025, 12:06 AM