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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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 According to the standard you're not allowed to cast from a function pointer to void * and vice versa.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.