Casting function ptrs
John F. Haugh II
haugj at pigs.UUCP
Sat May 21 05:49:20 AEST 1988
In article <280 at marob.MASA.COM>, daveh at marob.MASA.COM (Dave Hammond) writes:
> Given a list of varying typed functions, their names and addresses:
>
> struct funcs {
> char *name;
> unsigned (*func)();
> }
> char *foo();
> struct funcs f = { "foo", (char *)foo };
the field `func' is `pointer to function returning unsigned'. assigning
anything else to it, such as a pointer to a function returning a pointer
to a character, as you do in the example above, is wrong.
> And a routine which is passed a function name in order to lookup and return
> its associated address:
>
> unsigned *lookup_func(name)
> char *name;
> {
> ...
> return( (unsigned *) f->func );
> }
this is also incorrect. lookup_func should have its return value the same
type as f->func. the correct declaraction for lookup_func is
unsigned *(*lookup_func()) (name)
char *name;
{
...
}
> How does one declare the lookup function, the return address variable and
> call the returned function, while properly casting the function return value?
> I'm doing it like so:
> unsigned *lookup_func();
> unsigned *(*func)();
> char *retp;
>
> if ((func = lookup_func("foo")) != (unsigned *)0) {
> if (( retp = (char *) (*func)() ))
> printf("retp=%s",retp);
> }
the return address variable has the same type as f->func, which is `pointer
to function returning pointer to unsigned', or
unsigned *(*retp) ();
> Yes? No? Gonna blow up on me at some point ?
>--
> Dave Hammond
the people at ANSI land will tell you can't go converting between different
types of pointers and expecting ``reasonable'' results. so, yes, it will
blow up on you at some point.
i suggest you find a copy of the `cdecl' program. it can come in very
handy for writing casts and function and variable declarations. it also
comes in handy for writing USENET articles ;-)
- john.
--
The Beach Bum Big "D" Home for Wayward Hackers
UUCP: ...!killer!rpp386!jfh jfh at rpp386.uucp :SMAILERS
"You are in a twisty little maze of UUCP connections, all alike" -- fortune
More information about the Comp.unix.questions
mailing list