Link to home
Start Free TrialLog in
Avatar of b_acs
b_acsFlag for United States of America

asked on

How do you create a menu that uses an array of function pointers?

I'm trying to create a program with a menu that uses an array of function pointers.  So when the user selects an option the appropriate function is called.  I know that I am close to figuring this out, but just haven't quite got it.  (I know that I could use a switch statement but I'm suposed to use this array.)  Please tell me what's wrong with my code.  Also is there another way that I can initialize each element in my char array to "none"?
const int size = 10;
const int length = 25;
char Name[size][length] = {"none","none","none","none","none","none","none","none","none","none"};
 
int main()
{
	int Option = 0;
		
	int (*fptr[6])(char[size][length]) = {Add, Update, Delete, Sort, Print, Quit};//declaration creating array of fuction pointers
	
	do 
	{ 
		system("cls");
		cout << "Main Menu",
		cout << "\n",
		cout << "1) Add\n",
		cout << "2) Update\n",
		cout << "3) Delete\n",
		cout << "4) Sort\n",
		cout << "5) Print\n",
		cout << "6) Quit\n" << endl;
		
		cout << "Enter Selection" << endl;
		cin >> Option;
 
		if(Option < 1 || Option > 6)
		{
			cout << "invalid entry - please re-enter" << endl;
		}		else
		{
			cout << fptr[Option - 1]() << endl;
		}
 
 
		}while(Option != 6);
 
	return 0;
 
}

Open in new window

Avatar of mgonullu
mgonullu
Flag of United Arab Emirates image

Why you are doing in the hard way and not just use Switch statement?
Regarding the initialization of your array why not use a nested for loop
Avatar of Zoppo
Hi b_acs,

I think you need to write '(*fptr[Option - 1])()' to call the functions via their pointer.

Hope that helps,

ZOPPO
ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> Why you are doing in the hard way and not just use Switch statement?

Using function pointers for this kind of stuff is cleaner. You don't need a switch.
Avatar of b_acs

ASKER

I knew I was close!  Thank you!
Btw, instead of having something like this :

        int (*fptr[6])(char[size][length])

do yourself a favor, and make your life a little easier by using typedef's :

        typedef int (*MenuFunction)(char[size][length]);

This typedef is the function pointer as you defined it. You can then simply create an array of function pointers like this :

        MenuFunction fptr[6] = { ... };

Much easier to read and understand ;)