-
Function Pointers
Hello. I haven't had much trouble with function pointers in the past, but now they are a major pain. Could anyone tell me what I am doing wrong in the below code and give a fixed version please. I get a compiler error that I will also post below. Thanks in advance.
Code:
int test(int x)
{
return 0;
}
int function(char* string)
{
//...
return test; // Returns the address of test.
}
int main(void)
{
int (*pointer) (int);
pointer = (void *)function("Hello World");
//...
}
Error
Code:
error: invalid conversion from `int' to `int (*)(int)'
How would I fix this. Its really giving me a headache. I've been trying to figure this out for hours now.
-
http://www.newty.de/fpt/index.html
The first thing I would suggest is always create typedefs for your function pointer types. They get pretty hairy at times, and there's always an excess of ( ) to deal with.
Code:
typedef int (*fnType)(int);
int test(int x)
{
return 0;
}
fnType function(char* string)
{
//...
return test; // Returns the address of test.
}
int main(void)
{
fnType pointer;
pointer = function("Hello World");
return 0;
}
-
Quote:
Originally Posted by
johnnymckinney2
Code:
int main(void)
{
int (*pointer) (int);
pointer = (void *)function("Hello World");
//...
}
You call function(). This returns an int. You cast this to a void * for some reason, then try to stick it in a function pointer. No wonder it doesn't work.
Code:
int main(void)
{
int (*pointer)(int);
pointer = (int (*)(int))function;
}
Try that.
-
And of course, assuming that an int is the same size as a pointer may not work right on all systems. It would be better to return a pointer of some type - perhaps a function pointer type - using typedef like Salem suggested, or like this:
Code:
int test(int x)
{
return 0;
}
int (*)(int) function(char* string)
{
//...
return test; // Returns the address of test.
}
int main(void)
{
int (*pointer) (int);
pointer = function("Hello World");
//...
}
--
Mats