[英]Function pointer pointing to functions with different number of arguments
[英]function pointer array with different number of arguments
我想用下面的代碼替換下面的 switch case 語句
switch (n)
{
case 0:
i2c_scan();
break;
case 1:
i2c_read(45);
break;
case 2:
i2c_write(45,5);
break;
default:
printf("\nwrong input\n");
break;
}
請檢查以下代碼
#include<stdio.h>
void i2c_scan()
{
printf("\ni2c scan\n");
}
void i2c_read(int x)
{
x= x+1;
printf("\ni2c read: %d\n",x);
}
void i2c_write(int x , int y)
{
x=x+y;
printf("\ni2c write:%d\n",x);
}
int main() {
int n;
void (*fun_ptr_arr[])() = {i2c_scan,i2c_read,i2c_write};
(*fun_ptr_arr[0])(45,5); //have put array index to show results ,i could have took input from user and put it here like switch case: case number)
(*fun_ptr_arr[1])(45,5);
(*fun_ptr_arr[2])(45,5);
}
Output:
i2c 掃描
i2c 讀取:46
i2c 寫入:50
當我傳遞更多 arguments 然后需要 function 時,上面的代碼如何編譯和運行而沒有任何錯誤? 它是如何正常工作的,就像 i2c_read 接受第一個參數並給出結果一樣?
當我傳遞更多 arguments 然后需要 function 時,上面的代碼如何編譯和運行而沒有任何錯誤?
正如@DanBrezeanu wells 指出的那樣,行為是UB。
任何事情都可能發生,包括顯然“正常工作”。
宣言
void (*fun_ptr_arr[])()
意味着fun_ptr_arr
是一個指向函數的指針數組,其形式如下:
void f() { ... }
void g() { ... }
這不同於:
void f(void) { ... }
void g(void) { ... }
這個答案更詳細,但要點是:第二種形式是 function,不接受 arguments,而第一種形式接受任意數量的 arguments。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.