1

I am trying to pass a function pointer as part of a number of arguments under va_arg. I tried using a void * wildcard, before typecasting it later, but that gives an error.

   fn_ptr = va_arg(*app, (void*));

How does one pass a function pointer, as an argument to another function using va_args?

jhtong
  • 1,529
  • 4
  • 23
  • 34

1 Answers1

1

Just pass the type of the function pointer to va_arg. For example:

#include <stdio.h>
#include <stdarg.h>

void foo()
{
    printf("foo\n");
}

typedef void(*foo_ptr)();

void bar(unsigned count, ...) 
{
    va_list args;
    va_start(args, count);
    unsigned i = 0;

    for (; i < count; ++i) {
        foo_ptr p = va_arg(args, foo_ptr);
        (*p)();
    }
    va_end(args);
}

int main() 
{
    bar(2, &foo, &foo);
}

Live demo

Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • Great, thanks! Realized that in the definition of `va_arg`, the second argument must not be bracketed i.e. `void *` instead of `(void *)` to work. – jhtong Mar 07 '14 at 08:41
  • @jhtong According to the standard you're [not allowed](http://stackoverflow.com/a/13697654/241631) to cast from a function pointer to `void *` and vice versa. – Praetorian Mar 07 '14 at 09:08