jhtong
jhtong

Reputation: 1589

Passing function pointer as an argument using va_args

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?

Upvotes: 1

Views: 679

Answers (1)

Praetorian
Praetorian

Reputation: 109289

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

Upvotes: 1

Related Questions