|
|
On Mar 28, 1:00 pm, pete <pfil...@xxxxxxxxxxxxxx> wrote:
> Bartc wrote:
>
> > I'm having problems with the following code.
>
> > I have a table of function pointers, and a function pointer variable p which
> > steps through the functions.
>
> > But I'm not allowed to increment the variable using ++p.
>
> > What's the problem here?
>
> > Also, I may not be interested in returning from any of these functions (each
> > will call the next according to some global variable). Any recommended way
> > of doing this (throwing away return address) other than a crude asm("pop
> > R")?
>
> > Thanks,
>
> > Bart.
>
> > #include <stdio.h>
> > #include <stdlib.h>
>
> > void f1(void);
> > void f2(void);
> > void f3(void);
> > void f4(void);
>
> > int main(void)
> > {
> > void (*table[])(void)={&f1,&f2,&f3,&f4}; /* table of function pointers */
> > void (*p)(void); /* pointer to one of the functions (I hope) */
>
> > p=table[0];
>
> > while(1)
> > { (*p)(); /* Call function @p */
> > ++p; /* COMPILE ERROR HERE */
> > };
>
> > }
>
> > void f1(void){puts("F1 CALLED");return;};
> > void f2(void){puts("F2 CALLED");return;};
> > void f3(void){puts("F3 CALLED");return;};
> > void f4(void){puts("F4 CALLED"); exit(0);};
>
> /* BEGIN new.c */
>
> #include <stdio.h>
> #include <stdlib.h>
>
> void f1(void);
> void f2(void);
> void f3(void);
> void f4(void);
>
> int main(void)
> {
> void (*table[])(void) = {
> f1, f2, f3, f4
> };
> void (**p)(void);
>
> p = table;
> while (p != table + sizeof table / sizeof *table) {
> (*p++)();
> }
> return 0;
>
> }
>
> void f1(void)
> {
> puts("F1 CALLED");
>
> }
>
> void f2(void)
> {
> puts("F2 CALLED");
>
> }
>
> void f3(void)
> {
> puts("F3 CALLED");
>
> }
>
> void f4(void)
> {
> puts("F4 CALLED");
>
> }
>
> /* END new.c */
I like to use typedefs for arrays of function pointers.
#include<math.h>
#include<stdio.h>
typedef double (*f_t) (double);
static f_t f[] = {log, log10, sqrt, cos, cosh, exp, sin, sinh, tan,
tanh, 0};
int main(void)
{
int i;
f_t *flist = f;
for (i = 0; f[i]; i++) {
printf("function %d of 0.5 = %g\n", i, f[i] (0.5));
printf("function %d of 0.5 = %g\n", i, (*f[i]) (0.5));
}
while (*flist) {
f_t ff = *flist;
printf("current function of 0.5 = %g\n", ff(0.5));
flist++;
} return 0;
}
|
|