C Programming: Forward variable argument list

CVariablesArgumentsPrintfForward

C Problem Overview


I'm trying to write a function that accepts a variable number of parameters like printf, does some stuff, then passes the variable list to printf. I'm not sure how to do this, because it seems like it would have to push them onto the stack.

Something approximately like this

http://pastie.org/694844

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

void forward_args( const char *format , ... ){
  va_list arglist;
  printf( format, arglist );
}


int main (int argc, char const *argv[]){
  forward_args( "%s %s\n" , "hello" , "world" );  return 0;
}

Any ideas?

C Solutions


Solution 1 - C

Don't pass the results to printf. pass them to vprintf. vprintf specifically exists to handle passing in va_list arguments. From the Linux man page:

#include <stdio.h>

int printf(const char *format, ...);
int fprintf(FILE *stream, const char *format, ...);
int sprintf(char *str, const char *format, ...);
int snprintf(char *str, size_t size, const char *format, ...);

#include <stdarg.h>

int vprintf(const char *format, va_list ap);
int vfprintf(FILE *stream, const char *format, va_list ap);
int vsprintf(char *str, const char *format, va_list ap);
int vsnprintf(char *str, size_t size, const char *format, va_list ap);

Notice how the latter explicitly take va_list arguments such as the ones you declare inside a function taking ... in the parameter list. So your function would be declared like this:

void forward_args( const char *format , ... ){
   va_list arglist;
   va_start( arglist, format );
   vprintf( format, arglist );
   va_end( arglist );
}

Solution 2 - C

I'm pretty sure you're looking for va_start() / vprintf() / vsnprintf() / va_end(), there's no need to implement these yourself.

Solution 3 - C

You'll be passing along the arglist value to a function designed to consume it. See the stdarg and vprintf documentation for more clues.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoshua CheekView Question on Stackoverflow
Solution 1 - CquarkView Answer on Stackoverflow
Solution 2 - CTim PostView Answer on Stackoverflow
Solution 3 - Cuser202929View Answer on Stackoverflow