Gaurav Gaurav - 3 months ago 15
C Question

passing function with variable parameter as void pointer, and calling it

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;
}

Answer

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;
}