I have a list of different functions in my main()
:
puzzle1(ar);
puzzle2(ar);
puzzle3(ar);
puzzle4(ar);
puzzle5(ar);
I want to randomly pick only one of the functions to be called. What should I do to make this happen?
Thank you!
EDIT 1:My functions are all 2D-Arrays
EDIT 2: Got more help from comments.
EDIT 3:After more help, I've done the following:
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);
What am I doing wrong? Errors I'm obtaining are :
expected declaration specifier or '.....' before 'time'
on the srand
line
initializer element is not constant
on the int rand_output
line
subscripted value is neither array nor pointer nor vector
on the (*fp[rand_output])(x,y)
line
and a bunch of warning that says initialization from incompatible pointer type
Use rand()
to select one index and call the function at that index from a list of function pointers.
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);
Or simply in one line:-
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);
}