I just can't figure out how to pass an Argument like in the following scenario:
#include<stdio.h> void quit(const char*); int main(void){ const char *exit = "GoodBye"; void (*fptr)(const char*) = quit; (*fptr)(exit); return 0; } void quit(const char *s){ printf("\n\t%s\n",s); } This is how my program should work and it does, but when I make a text menu i just can't figure out how to do it:
#include<stdio.h> #include<stdlib.h> int update(void); int upgrade(void); int quit(void); void show(const char *question, const char **options, int (**actions)(void), int length); int main(void){ const char *question = "Choose Menu\n"; const char *options[3] = {"Update", "Upgrade", "Quit"}; int (*actions[3])(void) = {update,upgrade,quit}; show(question,options,actions,3); return 0; } int update(void){ printf("\n\tUpdating...\n"); return 1; } int upgrade(void){ printf("\n\tUpgrade...\n"); return 1; } int quit(void){ printf("\n\tQuit...\n"); return 0; } void show(const char *question, const char **options, int (**actions)(void), int length){ int choose = 0, repeat = 1; int (*act)(void); do{ printf("\n\t %s \n",question); for(int i=0;i<length;i++){ printf("%d. %s\n",(i+1),options[i]); } printf("\nPlease choose an Option: "); if((scanf("%d",&choose)) != 1){ printf("Error\n"); } act = actions[choose-1]; repeat = act(); if(act==0){ repeat = 0; } }while(repeat == 1); } Here I need to change the quit function (int quit(void); to int quit(char *s){};) like in the First example and call it with an argument like const char *exit = "GoodBye"; ==>> (*fptr)(exit);
I know that at this point my program takes only void as argument, but I done it only to illustrate the problem.
I'm very confused about this.
EDIT:
this int (*actions[3])(void) I think is an Array of Function pointers and all 3 function pointers takes void as argument, but I need to know if i can use one pointer to take an argument or i have to re-code the whole program.
exitconfused me for a moment. There's a standard functionexit()declared in<stdlib.h>. Your code would work even if you included<stdlib.h>, but you'd not be able to call theexit()function from withinmain()with the declaration of the stringexitinmain(). Not technically wrong — but IMO ill-advised.int (*actions[3])(void), like any array, decays into a pointer to the first element. So the function can simply take aint (*)(void)parameter.