我的 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/