c - C编程中随机选择一个预置函数

标签 c stdio

我的 main() 中有一个不同函数的列表:

puzzle1(ar); 
puzzle2(ar); 
puzzle3(ar); 
puzzle4(ar); 
puzzle5(ar);

我想随机选择仅一个函数来调用。我应该怎么做才能做到这一点?

谢谢!

编辑 1:我的函数都是二维数组

编辑 2:从评论中获得更多帮助。

编辑 3:在获得更多帮助后,我完成了以下操作:

srand(time(NULL));
int rand_output = rand()%5;
int (*fp[5])(char finalpuzzle[NROW][NCOL]);


int main();

char ar[NROW][NCOL];
int x,y,fp=0;

    fp[0]=puzzle1;
    fp[1]=puzzle2;
    fp[2]=puzzle3;
    fp[3]=puzzle4;
    fp[4]=puzzle5;
    (*fp[rand_output])(x,y);

我做错了什么? 我得到的错误是:

expected declaration specifier or '.....' before 'time'

srand

initializer element is not constant

int rand_output

subscripted value is neither array nor pointer nor vector

(*fp[rand_output])(x,y)

还有一堆警告说 initialization from incompatible pointer type

最佳答案

使用 rand() 选择一个索引并从函数指针列表中调用该索引处的函数。

srand(time(NULL));   // called once
int rand_output = rand()%5; 
int (*fp[5]) (int ar[]);

..
..
fp[0]=puzzle1;
fp[1]=puzzle2;
..

(*fp[rand_output])(arr);

或者简单地在一行中:-

 int (*fp[5])(int[])={puzzle1, puzzle2,. ...., puzzle5};

一个小示例代码

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

void op1(int ar[][2]){
    printf("%s","ok");
}
void op2(int ar[][2]){
    printf("%s","ok2");
}
int main(){
    int z[2][2]={{0,1},{2,4}};
    srand(time(NULL));   // called once
    int rand_output = rand()%2; 
    void (*fp[2]) (int ar[][2]);
    fp[0]=op1;
    fp[1]=op2;
    (*fp[rand_output])(z);
}

关于c - C编程中随机选择一个预置函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47240437/

相关文章:

c - 数据类型和格式说明符

c++ - 无符号和有符号短整型的位宽

c - 一些简单的逻辑问题并打印一些东西 C++ HouseWindowsLab

c - 为什么使用 printf ("mystring\n") 而不是仅仅 put ("mystring")?

c - 如何用C检测你的机器是否是32位

C++ "Building a series to solve a function"为什么我的近似值不对?

c - 非常简单的纯 C 非负整数解析器的非常奇怪的行为

c - 从文件句柄获取真实路径

C编程,如何在等待用户输入时运行for循环

c - 在 get_line 实现中,如何允许用户移动光标?