Variable arguments

F

frank

I am declaring a local buffer of a fixed size in my variable argument
routine. How do I figure out the correct size of the variable argument list
so that I can dynamically allocate the memory?

void disp_message(char *szCaption, char *szFormat, ...)
{
va_list ap;
char szBuffer[4096] = { 0 };

va_start(ap, szFormat);
vsprintf(szBuffer, szFormat, ap);
va_end(ap);

// Display the message.
MessageBox(NULL, szBuffer, szCaption, MB_OK | MB_ICONWARNING);
}
 
E

Eric Sosman

frank said:
I am declaring a local buffer of a fixed size in my variable argument
routine. How do I figure out the correct size of the variable argument list
so that I can dynamically allocate the memory?

Try vsnprintf(). It's a C99 addition, but is available
in some pre-C99 implementations, too. Use some caution with
pre-C99 versions, since their semantics may not be exactly
those that were eventually codified in the C99 Standard.
void disp_message(char *szCaption, char *szFormat, ...)
{
va_list ap;
char szBuffer[4096] = { 0 };

The initialization is pointless (because you're about
to overwrite the buffer anyhow) and potentially wasteful
(because you're about to overwrite all those carefully-
inserted zeroes).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,269
Latest member
vinaykumar_nevatia23

Latest Threads

Top