首页 > 解决方案 > C 语言 - 基于作为参数传递的索引值调用函数 - 指向函数的指针数组

问题描述

感谢您花时间阅读本文,我在发布之前寻找答案,但我对这门语言非常陌生。我正在尝试做的这个练习来自“Effective C: An Introduction to Professional C Programming”一书。

这是我第一次学习语言,本书第2章的练习如下:

声明一个由三个指向函数的指针组成的数组,并根据作为参数传入的索引值调用适当的函数

我不完全确定我理解它在说什么,但我有一段我认为可以完成工作的功能代码。但是,我不确定我是否正确解释了它。这是我的代码:

#include <stdio.h>
#include <stdlib.h>

void f0(int x) {
  printf("I am f0 and in index location %d\n", x);
}

void f1(int x) {
  printf("I am f1 and in index location %d\n", x);
}

void f2(int x) {
  printf("I am f2 and in index location %d\n", x);
}

int main(void){

  void (*f0p)(int);
  f0p = &f0;

  void (*f1p)(int);
  f1p = &f1;

  void (*f2p)(int);
  f2p = &f2;

  void *array[3] = {f0p, f1p, f2p};

  for (int i = 0; i < 3; i++) {
    void (*program)(int);
    program = array[i];
    program(i);
  }
  
  return 0;
}

这在编译后工作并返回以下内容:

I am f0 and in index location 0
I am f1 and in index location 1
I am f2 and in index location 2

但是,我是否正确地完成了练习?我不认为我在技术上使用索引作为参数并调用函数,但我是一个菜鸟。您提供的任何验证或更正/教育将不胜感激。我今天花了很多时间在这上面!

标签: arrayscfunctionpointers

解决方案


指针不应在指向函数的指针和指向对象的指针(包括void)之间转换,除非在特殊情况下。

最好将该数组声明为指向函数的指针数组:

void (*arrray[])(int) = { f0, f1, f2 };

并且可以在没有中间变量的情况下调用函数:

array[i](i);

推荐阅读