Re: Problem with pointer to function - what's wrong here?
- From: Eric Sosman <Eric.Sosman@xxxxxxx>
- Date: Wed, 31 Jan 2007 17:07:27 -0500
Charles Sullivan wrote On 01/31/07 16:27,:
I define and initialize an array of structures like the following,
(where the <verbiage within angle brackets> is just meant to be
explanatory):
int func1(<argument prototypes>);
int func2(<argument prototypes>);
struct mystruct {
<other stuff>;
int (*myfunc)();
} myrecords[] = {
{<other stuff value>, func1},
{<other stuff value>, NULL },
{<other stuff value>, func2}
};
int func1(<argument list>)
{
<blah-blah-blah1>
}
int func2(<argument list>)
{
<blah-blah-blah2>
}
I've always believed this was legal code, and have used something
similar a few times in the past, but now when (<argument list>) is:
(unsigned char x1, unsigned char x2, unsigned char x3,
int *y1, unsigned int *y2, int *y3)
I get the compiler message:
"warning: initialization from incompatible pointer type"
What am I doing wrong?
Ben Pfaff has explained the error; here are suggestions
for a few fixes.
If all the (<argument prototype>) lists are identical, that's
the easiest case: just change the myfunc declaration inside the
struct to
int (*myfunc)(<argument prototypes>);
and all will be well. ("Identical" in argument count and types;
argument names, if any, don't matter.)
If the prototypes for func1(), func2(), etc. are not the
same, it's a bit harder. In the initializer list, you need to
convert each function pointer to the expected type:
{<other stuff value>, (int(*)())func1},
{<other stuff value>, (int(*)())NULL},
{<other stuff value>, (int(*)())func2},
You could improve the readability by introducing a typedef for
the function pointer casts; also, the cast of NULL isn't really
needed.
But that's not all! At the point where you actually use
the function pointer to call the pointed-to function, you need
to convert it back to the defined type of that called function.
This means you need some way of figuring out what that type is
supposed to be, perhaps with a type code in the <other stuff>.
Then you could write something like
switch (myrecords[i].type) {
case ONE_INT:
result = ((int(*)(int))myrecords[i].myfunc)(42);
break;
case TWO_DOUBLES:
result = ((int(*)(double,double))myrecords[i].myfunc)
(42.0, sqrt(42.0));
break;
...
Again, typedefs might improve the readability.
--
Eric.Sosman@xxxxxxx
.
- References:
- Problem with pointer to function - what's wrong here?
- From: Charles Sullivan
- Problem with pointer to function - what's wrong here?
- Prev by Date: Re: Problem with pointer to function - what's wrong here?
- Next by Date: Re: Does Casting Slow a Program Down?
- Previous by thread: Re: Problem with pointer to function - what's wrong here?
- Index(es):
Relevant Pages
|