Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!apple!olivea!orc!inews!iwarp.intel.com!gargoyle!chinet!john From: john@chinet.chi.il.us (John Mundt) Newsgroups: comp.lang.c Subject: Re: Functions within structures Keywords: structures Message-ID: <1990Nov10.155153.20639@chinet.chi.il.us> Date: 10 Nov 90 15:51:53 GMT References: <2203@abcom.ATT.COM> Organization: Chinet - Public Access UNIX Lines: 59 In article <2203@abcom.ATT.COM> mdb@abcom.ATT.COM (5013 ) writes: > I need help. I am building a menu using structures and would like > to be able to include the function to be run within the structure. .... > >int add_rec(); >int find_rec(); >int quit(); > >unsigned int records=0; >typedef struct { > char key; > int x_row; > int y_row; > char msg[20]; int (*fptr)(); /* add this to your structure prototype */ >} MENU; > >MENU menu[MENU_ITEM+1] = { > { '1',7,25,"Add Phone Number",add_rec }, > { '2',9,25,"Find Phone number",find_rec }, > { 'Q',12,25,"QUIT",quit } > } ; Notice that the ()'s were removed from the functions. > >Now, how do I assigned these functions to the structure (or is it posible) >and then access these same functions? Any help will be greatly appreciated. The functions are now assigned, so that menu[whatever].fptr is the function. You can use the function thusly, { int some_value; some_value = (*menu[whatever].fptr)(); } since menu[whatever].fptr is the address of the function, and *menu[whatever].fptr is the function. K&R says it better. Lint and/or your compiler may or may not complain about this. Seems to depend on the machine. 3b2's like it, 3b1's do not. 386's don't like it, but in all cases it works. As an aside, some_value = (*menu[whatever].fptr)(); some_value = (menu[whatever].fptr)(); produce the same assembler code on at least one machine, and both work, though the first one is the one that is considered correct. -- --------------------- john@admctr.chi.il.us John Mundt Teachers' Aide, Inc. P.O. Box 1666, Highland Park, IL (708) 998-5007 || -432-8860