I have a function which I want to pass through various functions
int func1(char *ptr)
{
printf("%s",ptr);
return 0;
}
and other function in which I want to call the func1
int func2(void *i)
{
//call i
//here i point to function func1
//and do something with return value of i
}
So, how should I call it in main()?
int main()
{
void *d;
//SOMETHING wrong in next four line
d=&func1("abcd");
func2(d);
d=&func1("xyz");
func2(d);
return 0;
}
You can simply create a function (func2
) that takes a function pointer to your desired function that you want called and another paramter that takes a pointer to your string. Then in func2
call the passed in function pointer with the str
argument.
#include <stdio.h>
void func1(const char *str)
{
puts(str);
}
void func2(void (*fp)(const char *), const char *str)
{
fp(str);
}
int main(void)
{
const char *str = "Hello world.";
func2(func1, str);
return 0;
}
First of all: A function pointer refers to a function only. Parameters come into the game when the function is called, either directly or via a function pointer.
So if you want to achieve what you have in mind, that is binding a (set of) parameters to a specific function varaible you need to use a wrapper function:
int func1(char * pc)
{
int i;
/* assigne somehting to "i" and use "pc" */
return i;
}
int func1_abcd(void)
{
return func1("abcd")
}
int func1_xyz(void)
{
return func1("xyz")
}
typedef int (*pfunc1_wrapper_t)(void);
int func2(pfunc1_wrapper_t pfunc1_wrapper)
{
return pfunc1_wrapper();
}
int main(int argc, char ** argv)
{
pfunc1_wrapper_t pfunc1_wrapper = NULL;
int i = 0;
pfunc1_wrapper = func1_abcd;
i = func2(pfunc1_wrapper);
pfunc1_wrapper = func1_xyz;
i = func2(pfunc1_wrapper);
...
return 0;
}
You should first of all use Function pointers to do the job you desire. Using void pointer is a method where you before hand know what you will cast it to for dereferencing. Since you are passing the address of a function, you should cast it to a function pointer anyways. So avoid all this and declare func pointer anyways. Use void * only if you know that you can handle all the possiblities. eg. memcpy uses void * this is acceptable as you just want a bunch of data in soure location to be copied to a destination location.
#include <stdio.h>
void func1(char * str)
{
printf("%s",str);
}
void func2(void * g)
{
void (*p) (char *); //function pointer
p = (void (*)(char *))g;//casting void * to pi.e func pointer reqiuired eitherways.
p("Func pointer caller");
}
void main()
{
void * d = func1; // name of the function is itselt its address
//printf("func1 = %d\nd = %d",func1,d);
func2(d);
}
all this can be avoided by a simple function pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With