Re: De-referencing pointer to function-pointer
From: Edd (eddNOSPAMHERE_at_nunswithguns.net)
Date: 05/12/04
- Next message: Ben Pfaff: "Re: De-referencing pointer to function-pointer"
- Previous message: Leor Zolman: "Re: Why does execution start at main()?"
- In reply to: Jack Klein: "Re: De-referencing pointer to function-pointer"
- Next in thread: Edd: "Re: De-referencing pointer to function-pointer"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 12 May 2004 05:13:51 +0100
Jack Klein wrote:
[ 8< - - - snip ]
> No, no, no, no. There is no correspondence between pointers to object
> types and pointers to functions in C. Even attempting to convert
> between a function pointer and a pointer to void, in either direction,
> is completely undefined.
Apologies for that. I keep meaning to get a copy of the standard, but I'm a
bit strapped for cash at the moment. I'll have one soonish though, with any
luck. Should save on your mental anguish... :)
> Fortunately, you don't need to. You already have a perfect operand
> here, just replace the line above with:
>
> InitArray(&funcs, sizeof f);
>
> f is already a pointer to function, not the name of a function, so
> applying sizeof to it is just fine and dandy. Also, since f is an
> object and not a type, the parentheses are not necessary, but harmless
> if you prefer them.
>
>> /* Add some functions to the funcs ARRAY */
>> vptr = sin;
>> AddElement(&funcs, &vptr);
>> vptr = tan;
>> AddElement(&funcs, &vptr);
>> vptr = exp;
>> AddElement(&funcs, &vptr);
>> vptr = log;
>> AddElement(&funcs, &vptr);
>
> Leave out vptr completely, just omit if from your program. Now that
> you have uses sizeof f to initialize your structure, you can just do:
>
> AddElement(&funcs, sin);
> AddElement(&funcs, tan);
>
> ...and so on.
>
> No problem with using the name of a function without () as an argument
> passed to another function. Unlike with the sizeof operator, this is
> well defined and automatically converts the name of the function to a
> pointer to the function.
[ 8< - - - snip ]
> To retrieve a function pointer from your array, you can get rid of all
> that almost indecipherable casting by doing this:
>
> void *vp;
> vp = GetElement(&funct, 2);
> memcpy(&f, vp, sizeof f);
>
> The latter two lines can be combined, with rather less readability, to
> eliminate the need for the pointer to void:
>
> memcpy(&f, GetElement(&func, 2), sizeof f);
>
> All the nasty casts are gone!
That's all splendid, Jack, thanks very much!
Edd
- Next message: Ben Pfaff: "Re: De-referencing pointer to function-pointer"
- Previous message: Leor Zolman: "Re: Why does execution start at main()?"
- In reply to: Jack Klein: "Re: De-referencing pointer to function-pointer"
- Next in thread: Edd: "Re: De-referencing pointer to function-pointer"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|