0

I have a module with a a variable number of parameters:

int myprintf( const char *format, ...  ){

}

I want to declare a local char array, pass the "myprint" parameters to sprintf() so that sprintf() converts the parameters to a character array then I can do something with that character array. By doing this, I do not have to re-invent the internals of sprintf.

In theory:

int myprintf( const char *format, ...  )

{
    char buf[ 512 ];

    sprintf( buf, format, ... );

  // now do something with buf

}

I am sure va_start( a, b), va_arg( c, d ) will have something to do with it; but va_arg seems to need parse the original argument list.

Any suggestions?

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331

2 Answers2

2

To elaborate on what Chris said, something like:

int vmyprintf(const char* format, va_list args)
{
        char buf[512];

        vsnprintf(buf, sizeof(buf), fmt, args);
        // now do something with buf 
}

int myprintf(const char *format, ...)
{
        va_list args;
        int ret;

        va_start(args, format);
        ret = vmyprintf(format, args);
        va_end(args);
        return ret;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Graham
  • 86
  • 1
  • 1
    This. Any variadic function should be wrapping a `va_list` function so that others can wrap it as well. – Medinoc Feb 26 '14 at 17:13
1

You are probably looking for something like that:

void myprintf( const char *format, ...  )
{
    char buf[ 512 ];

    va_list vl;
    va_start (vl, format);
    vsnprintf(buf, 511, format, vl);
    va_end(vl);

    // now do something with buf
}

Some other information is available in my answer here

Of course the above answer leave many issues open, for instance how will we handle buffer overflows or such. But this is another story.

Community
  • 1
  • 1
kriss
  • 23,497
  • 17
  • 97
  • 116