pointers to functions

Krishnakumar K. kk at amdcad.UUCP
Tue Jul 1 03:52:09 AEST 1986


In article <237 at killer.UUCP> toma at killer.UUCP (Tom Armistead) writes:
>Secondly is it possible to have an array of type 'pointer to' function.
>i.e. 
>int  (*function)()[SIZE];
>something like the above, I was able to achieve this using this:
>struct	fct {
>            int  (*func)();
>            } f_array[SIZE];
>function()
>{
>    int x;
>    printf("offset: ");
>    scanf("%d",&x);
>    (*f_array[x].func)();
>}
>Is there another way???
>
I'm currently involved in writing an interpreter to process numeric 
expressions.  When I encounter a function reference I need to translate
between that string and the 'C' function that will perform it.  The
following seems to work well.  I use a binary search of a function
table to keep it fast even for a large number of possible functions.

typedef struct {
	char *funcname;
	double (*func)();
} FUNCELEM;

extern double exp(), log(), sin(), cos();

FUNCELEM functable[] = {
	{ "cos", cos },
	{ "exp", exp },
	{ "log", log },
	{ "sin", sin }
};

extern double (*binary_search())();

double callfunc(name, arg) 
char *name;
double arg;
{
	double (*func)();

	func = binary_search(functable, name);
	if (func == NULL)
		return 0.0;
	else
		return (*func)(arg);
}

Brad Budlong.



More information about the Comp.lang.c mailing list