Reputation: 37
If I want to define a pointer variable p
to point to the function foo()
defined as below, what should be the exact type of p
?
int *foo(void *arg)
{
...
}
Upvotes: 2
Views: 136
Reputation: 121
Are you talking about pointer to function?
First define a pointer to function that takes void
argumenta and return int
typedef int (*Ptrtofun)(void);
Now safely can point this to your function.
Ptrtofun p;
p = &foo(void);
Now you have a ptr p
to function and can easily use it ..
Upvotes: 1
Reputation: 241691
Bearing in mind the comment of Kyrylo Polezhaiev, the type of p is
int*(*)(void*)
To declare p
, you need to insert the name at the correct point in the type:
int*(*p)(void*);
but it is generally more readable to use an alias:
typedef int*(func_t)(void*);
func_t* p;
Upvotes: 3
Reputation: 310940
To make it more easy you could for the function declaration
int *foo(void *arg);
define an alias named as for example Tfoo
that looks the same way as the function declaration itself
typedef int *Tfoo(void *);
After that to declare a function pointer to the function is very easy. Just write
Tfoo *foo_ptr = foo;
Otherwise you could write
typedef int * (* TFoo_ptr )(void *);
Tfoo_ptr foo_ptr = foo;
Or you could write a declaration of the function pointer directly without using the typedef/
int * (* foo_ptr )(void *) = foo;
Upvotes: 1
Reputation: 134286
You need to have the pointer as the pointer to a function, returning an int *
, accepting a void*
argument. You can make it like
int * (*p) (void *);
and then, you can use
p = foo;
Upvotes: 4