humblemark wrote:
I try to give a parameter in the function tt; but omething went
wrong?? Any idea what i can do??
The first thing you should do is read
<http://www.catb.org/~esr/faqs/smart-questions.html>.
Telling us that "something went wrong" is not particularly useful.
*What* went wrong?
As it happens, you've given us enough information to figure out the problem.
int ret_integer()
{
return 76;
}
Ok, ``ret_integer'' is a function returning an int. It has no
parameters, but it's better to make that explicit; I'd change the
declaration from ``int reg_integer()'' to ``int reg_integer(void)''.
(This isn't your main problem.
int (*tt(int dummy))()
``tt'' is a function that takes an int argument, and returns a pointer
to a function that returns an int. The returned function takes no
arguments; again, it's better to make this explicit:
int (*tt(int dummy))(void)
{
return ((int(*)()) ret_integer());
The expression ``ret_integer()'' *calls* your function and yields the
value that it returns (76, of type int). You then explicitly convert
the int value 76 to a pointer-to-function type, which gives you garbage.
What you want here is not ``ret_integer()'' (the result of calling the
function), but ``ret_integer'' (the name of the function, which decays
to a pointer to the function in this context).
I'm guessing that you added the cast to silence a compile-time error.
That should have made you suspicious. Most (but not all) casts are
actually unnecessary. All you need here is ``return ret_integer;''.
}
int main()
Ok, but ``int main(void)'' is preferred.
{ int(*pq)();
pq = tt(23);
pq(); // bang bang
And here you try to make a function call through the garbage pointer.
The result is undefined behavior (most likely your program crashes).
return 0;
}
Here's a version of your program that displays the result of the call:
#include <stdio.h>
int ret_integer(void)
{
return 76;
}
int (*tt(int dummy))(void)
{
return ret_integer;
}
int main()
{
int(*pq)(void) = tt(23);
printf("pq() returns %d\n", pq());
return 0;
}
--
Keith Thompson (The_Other_Keith)
ks***@mib.org
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"