我正在尝试从数组调用函数Greeting。有人可以给我一个提示或指导我在线观看视频或阅读。感谢
int Greeting()
{
printf("Hello, World!\n");
return 0;
}
int process[]={0,0,&Greeting,0,0,0};
int main()
{
process[2];
return 0;
}
答案 0 :(得分:3)
您的process
是int
的数组。你需要使它成为一个函数指针数组。
int (*process[])(void) = {0, 0, Greeting, 0, 0, 0};
然后间接调用该函数
process[2]();
答案 1 :(得分:1)
一个简单的例子,其中首先在结构中创建两个函数指针,然后创建三个函数。使用要调用的函数初始化函数指针,然后传递参数以完成工作。
#include <stdio.h>
typedef struct
{
/* Any function who take two int parameters and returns int can be pointed by this function pointer. */
int (*function_name)(int a, int b);
/* This can point to all functions having int argument and void return type */
void (*print_fn)(int sum);
} FN_GROUP;
int add(int a, int b)
{
return (a + b);
}
int subtract(int a, int b)
{
return (a - b);
}
void show(int num)
{
printf("Result:%d\r\n", num);
}
int main()
{
int num1 = 20;
int num2 = 10;
int result = 0;
FN_GROUP group;
/* Initialize the pointers with add() and show() functions. */
group.function_name = &add;
group.print_fn = &show;
/* Now call these functions. */
result = group.function_name(num1, num2);
group.print_fn(result);
/* Initialize the pointers with subtract(). */
group.function_name = &subtract;
/* Now call these functions again */
result = group.function_name(num1, num2);
group.print_fn(result);
return (0);
}