Question on function pointers

mcdonald at uxe.cso.uiuc.edu mcdonald at uxe.cso.uiuc.edu
Fri Aug 25 09:22:39 AEST 1989



>When I was experimenting out with function pointers in C, I came up with
>this  C code. I don't know how to cast the contents of a character pointer
>to function pointer ? Can this be done at all ? Logically it doesn't look
>possible for me. Can any netters enlighten on this ?

Casting a data pointer to a function pointer directly is illegal.
CAsting it to an appropriately long integer type and then casting THAT
to a function pointer is a legal operation, but the result of trying
to DO anything with the resulting function pointer is , most unfortunately,
not defined by the standard. It is even possible on some architectures
that the mere cast to a function pointer would load an illegal value
in some register somewhere, causing a dump, playing Rogue, or shooting
a missle at Mexico city. 

On the other hand, on architectures where it makes sense, it usually works:
MS-DOS and VMS come to mind. What is is good for, however, is not what
your example tries. You would want to cast a data pointer to a code pointer
if you have, somehow, gotten some CODE into a DATA array. This would
have been by actually COMPILING it in place (i.e. your program is
a compiler like Turbo or Quick C), you have read it in from a disk
array, etc. I have used this trick in many programs to do really
nifty things. But it is obviously not portable.

Doug McDonald



More information about the Comp.lang.c mailing list