跳轉到內容

C 語言入門/指向 C 函式的指標

來自華夏公益教科書,自由的教學資源

本檔案解釋瞭如何在 C 語言中宣告指向變數、陣列和結構體的指標。也可以定義指向函式的指標。此功能允許將函式作為引數傳遞給其他函式。例如,這對於構建一個函式來確定一系列數學函式的解很有用。

宣告指向函式的指標的語法很模糊,因此讓我們從一個過於簡化的例子開始:宣告指向標準庫函式“printf()”的指標。

   /* ptrprt.c */

   #include <stdio.h>

   void main()
   {
     int (*func_ptr) ();                  /* Declare the pointer. */
     func_ptr = printf;                   /* Assign it a function. */
     (*func_ptr) ( "Printf is here!\n" ); /* Execute the function. */
   }

函式指標必須宣告為與它所代表的函式相同型別(在本例中為“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()”。傳遞的函式必須與預期的引數數量和型別一致,以及與返回的值一致。

華夏公益教科書