Functions within structures
John Mundt
john at chinet.chi.il.us
Sun Nov 11 02:51:53 AEST 1990
In article <2203 at abcom.ATT.COM> mdb at 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 at admctr.chi.il.us
John Mundt Teachers' Aide, Inc. P.O. Box 1666, Highland Park, IL
(708) 998-5007 || -432-8860
More information about the Comp.lang.c
mailing list