繁体   English   中英

function 不同数量的 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM