CPB6 function with variable number of args

This is the forum for miscellaneous technical/programming questions.

Moderator: 2ffat

CPB6 function with variable number of args

Postby denville » Tue Oct 18, 2016 5:45 am

Please, how do I write somethin like this...

void MyPrintf( char* format, ... )
{
buf[80];

sprintf( buf, format, ..... );

(do something with buf, etc )
}
denville
Top Poster
Top Poster
 
Posts: 40
Joined: Sat Mar 06, 2010 4:40 am

Re: CPB6 function with variable number of args

Postby rlebeau » Tue Oct 18, 2016 11:00 am

You need to use vsnprintf/_s() instead of sprintf(). Use va_start() to initialize a va_list variable to point at the variable arguments, and then pass that list to vsnprintf/_s(). This also allows you to perform bounds checking so you don't overflow your buffer (or so you can allocate it dynamically).

Try this:

Code: Select all
void MyPrintf( char* format, ... )
{
    char buf[80];
    va_list args;
    int nSize;

    va_start(args, format);
    nSize = vsnprintf(buf, sizeof(buf), format, args);
    va_end(args);

    // do something with buf up to nSize characters ...
}


Or this:

Code: Select all
void MyPrintf( char* format, ... )
{
    char *buf = NULL;
    va_list args;
    int nSize;

    va_start(args, format);
    nSize = vsnprintf(NULL, 0, format, args);
    if (nSize > 0) {
        buf = new char[nSize+1];
        vsnprintf(buf, nSize+1, format, args);
    }
    va_end(args);

    // do something with buf up to nSize characters ...

    delete[] buf;
}
Remy Lebeau (TeamB)
Lebeau Software
User avatar
rlebeau
BCBJ Author
BCBJ Author
 
Posts: 1408
Joined: Wed Jun 01, 2005 3:21 am
Location: California, USA

Re: CPB6 function with variable number of args

Postby denville » Tue Oct 18, 2016 3:28 pm

As ever, thank you so much.

Denville.
denville
Top Poster
Top Poster
 
Posts: 40
Joined: Sat Mar 06, 2010 4:40 am


Return to Technical

Who is online

Users browsing this forum: Google [Bot] and 2 guests

cron