C語言中的函式指標



什麼是C語言中的函式指標?

在C語言中,指標是一個儲存另一個變數地址的變數。類似地,儲存函式地址的變數稱為函式指標指向函式的指標。當您想要動態呼叫函式時,函式指標很有用。C語言中回撥函式的機制依賴於函式指標。

函式指標像普通指標一樣指向程式碼。在函式指標中,可以使用函式名獲取函式的地址。函式也可以作為引數傳遞,也可以從函式中返回。

宣告函式指標

您應該有一個函式,您將要宣告其函式指標。要在C語言中宣告函式指標,請編寫一個宣告語句,其中包含返回型別、指標名稱以及它指向的函式的引數型別。

宣告語法

以下是宣告函式指標的語法

function_return_type(*Pointer_name)(function argument list)

示例

這是一個簡單的C語言中的hello()函式:

void hello(){
   printf("Hello World");
}

我們如下宣告指向此函式的指標:

void (*ptr)() = &hello;

現在,我們可以使用此函式指標“(*ptr)();”來呼叫該函式。

函式指標示例

以下示例演示瞭如何宣告和使用函式指標來呼叫函式。

#include <stdio.h>

// Defining a function
void hello() { printf("Hello World"); }

// The main code
int main() {
  // Declaring a function pointer
  void (*ptr)() = &hello;

  // Calling function using the
  // function poiter
  (*ptr)();

  return 0;
}

輸出

執行此程式碼時,將產生以下輸出:

Hello World

注意:與作為資料指標的普通指標不同,函式指標指向程式碼。我們可以使用函式名作為其地址(如陣列的情況)。因此,指向函式hello()的指標也可以如下宣告:

void (*ptr)() = hello;

帶引數的函式指標

也可以為具有引數的函式宣告函式指標。在宣告函式時,需要提供特定資料型別作為引數列表。

理解帶引數的函式指標

假設我們有一個名為addition()的函式,它有兩個引數:

int addition (int a, int b){

   return a + b;
}

要為上述函式宣告函式指標,我們使用兩個引數:

int (*ptr)(int, int) = addition;

然後,我們可以透過傳遞所需的引數來透過其指標呼叫該函式:

int z = (*ptr)(x, y);

請嘗試以下完整程式碼:

帶引數的函式指標示例

這是完整程式碼。它顯示瞭如何透過其指標呼叫函式:

#include <stdio.h>

int addition (int a, int b){
   return a + b;
}

int main(){

   int (*ptr)(int, int) = addition;
   int x = 10, y = 20;
   int z = (*ptr)(x, y);

   printf("Addition of x: %d and y: %d = %d", x, y, z);
   
   return 0;
}

輸出

執行此程式碼時,將產生以下輸出:

Addition of x: 10 and y: 20 = 30

指向具有指標引數的函式的指標

當主機函式本身具有指標引數時,我們也可以宣告函式指標。讓我們看看這個例子:

理解指向具有指標引數的函式的指標

我們有一個swap()函式,它使用它們的指標交換“x”和“y”的值:

void swap(int *a, int *b){
   int c;
   c = *a;
   *a = *b;
   *b = c;
}

按照宣告函式指標的語法,可以宣告如下:

void (*ptr)(int *, int *) = swap;

要交換“x”和“y”的值,請將它們的指標傳遞給上述函式指標:

(*ptr)(&x, &y);

指向具有指標引數的函式的指標示例

這是此示例的完整程式碼:

#include <stdio.h>

void swap(int *a, int *b){
   int c;
   c = *a;
   *a = *b;
   *b = c;
}

int main(){
   
   void (*ptr)(int *, int *) = swap;
   
   int x = 10, y = 20;
   printf("Values of x: %d and y: %d before swap\n", x, y);
   
   (*ptr)(&x, &y);
   printf("Values of x: %d and y: %d after swap", x, y);
   
   return 0;
}

輸出

Values of x: 10 and y: 20 before swap
Values of x: 20 and y: 10 after swap

函式指標陣列

您還可以根據以下語法宣告函式指標陣列

type (*ptr[])(args) = {fun1, fun2, ...};

函式指標陣列示例

我們可以使用透過指標動態呼叫函式的屬性,而不是使用if-elseswitch-case語句。請檢視以下示例:

#include <stdio.h>

float add(int a, int b){
   return a + b;
}

float subtract(int a, int b){
   return a - b;
}

float multiply(int a, int b){
   return a * b;
}

float divide(int a, int b){
   return a / b;
}

int main(){

   float (*ptr[])(int, int) = {add, subtract, multiply, divide};
   
   int a = 15, b = 10;
   
   // 1 for addition, 2 for subtraction 
   // 3 for multiplication, 4 for division
   int op = 3;
   
   if (op > 5) return 0;
   printf("Result: %.2f", (*ptr[op-1])(a, b));
   
   return 0;
}

輸出

執行程式碼並檢查其輸出:

Result: 150.00

將op變數的值更改為1、2或4以獲取其他函式的結果。

廣告