【问题标题】:function pointer array with different number of arguments具有不同数量参数的函数指针数组
【发布时间】:2020-08-16 18:32:40
【问题描述】:

我想用下面的代码替换下面的 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);
    
}

输出:

i2c 扫描

i2c 读取:46

i2c 写入:50

当我将更多参数传递给函数时,上面的代码如何编译和运行而没有任何错误?它是如何像 i2c_read 一样正常工作的?接受第一个参数并给出结果?

【问题讨论】:

  • 向 C 函数传递或多或少的参数被认为是未定义的行为。如果您真的想将可变数量的参数传递给函数,您应该查看variadic functions
  • 有几个人在this 线程中提到了它。那里有官方 C 文档的链接。

标签: c function-pointers


【解决方案1】:

当我将更多参数传递给函数时,上面的代码如何编译和运行而没有任何错误?

正如@DanBrezeanu wells 指出的那样,行为是 UB。
任何事情都可能发生,包括 显然“工作正常”。

【讨论】:

    【解决方案2】:

    声明

    void (*fun_ptr_arr[])()
    

    表示fun_ptr_arr 是一个指向函数的指针数组,形式如下:

    void f() { ... }
    void g() { ... }
    

    这与 不同

    void f(void) { ... }
    void g(void) { ... }
    

    This answer 详细阐述,但要点是:第二种形式是不接受参数的函数,而第一种形式接受任意数量的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-22
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      相关资源
      最近更新 更多