感谢您抽出宝贵的时间阅读本文,在发布之前我一直在寻找答案,但是我对该语言非常陌生。我正在尝试做的练习来自《有效的C:专业C编程入门》一书。
这是我第一次学习语言,本书第二章的练习如下:
声明一个由三个函数指针组成的数组,并根据作为参数传入的索引值调用适当的函数
我不能完全确定我理解它的意思,但是我有一段我认为可以完成工作的代码。但是,我不确定我是否正确解释了它。这是我的代码:
#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
但是,我可以正确完成练习吗?我不认为我在技术上使用索引作为参数并调用该函数,但我是菜鸟。您提供的任何验证或纠正/教育将非常感谢。我今天花了很多时间!
void
除非在特殊情况下,否则不应在函数指针和对象指针(包括)之间转换指针。
最好将数组声明为指向函数的指针数组:
void (*arrray[])(int) = { f0, f1, f2 };
并且可以在没有中间变量的情况下调用函数:
array[i](i);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句