C function pointer to function with varying number of arguments

This example C program illustrates the use of a function pointer to a variadic function (one which takes a variable number of arguments, in other words, has an ellipsis ... at the end of its list of arguments).

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

typedef int (*fprintf_t) (void * data, const char * format, ...);

int fprintf_like (void * data, const char * format, ...)
{
    int printed;
    va_list ap;
    va_start (ap, format);
    printed = vfprintf (stdout, format, ap);
    va_end (ap);
    return printed;
}

fprintf_t fprintf_ptr = fprintf_like;

int main (int argc, char ** argv)
{
    int i;
    for (i = 0; i < argc; i++) {
        (*fprintf_ptr) (0, "%d: %s\n", i, argv[i]);
    }
    return 0;
}

(download)


Copyright © Ben Bullock 2009-2018. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer