INF: Function Pointers to Functions with Different Parameters

ID Number: Q70142

5.00 5.10 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a

MS-DOS | OS/2

Summary:

The sample code below illustrates how to use function pointers to call

functions that take different parameters than those with which the

pointer was declared. The function is cast to the type of the function

pointer during the first assignment, then the function pointer is cast

to the type of the function to be called. Using typedefs generally

makes it easier than casting the pointer directly.

Sample Code

-----------

/* Compile options needed: none

*/

#include <stdio.h>

typedef int (*footype) (char *, char *);

typedef void (*gootype) (void);

typedef int (* fptype) (void);

int func1(char *, char *);

void func2(void);

void main(void)

{

fptype ptr;

ptr = (fptype) func1;

((footype) ptr)("one", "two");

ptr = (fptype) func2;

((gootype) ptr)();

}

int func1(char *a, char *b)

{

return printf("func1 took two parameters: %s and %s\n", a, b);

}

void func2(void)

{

printf("func2 did not take any parameters\n");

}

Additional reference words: 6.00 6.00a 6.00ax 7.00 argument list