Passing va_list two times?

A

Andrej Prsa

Hi!

If I declare two functions like this:

int execute_command (char *name, ...)
{
va_list args;

va_start (args, name);
my_func (1, args);
va_end (args);
}

int my_func (int argc, ...)
{
va_list args;
char *str;

va_start (args, argc);
str = va_arg (args, char *);
printf ("%s\n", str);
va_end (args);
}

and call them from e.g.

execute_command ("my_command", "my argument");

parsing of args is OK at the first function (e.g. if I cut & paste the
va_arg and printf part to the first function), but garbage is printed in
the second function. I'm surely missing something obvious, but I can't see
it. Help?

Thanks,

Andrej
 
M

Mike Wahler

Andrej Prsa said:
Hi!

If I declare two functions like this:

int execute_command (char *name, ...)
{
va_list args;

va_start (args, name);
my_func (1, args);
va_end (args);
}

int my_func (int argc, ...)
{
va_list args;
char *str;

va_start (args, argc);
str = va_arg (args, char *);
printf ("%s\n", str);
va_end (args);
}

and call them from e.g.

execute_command ("my_command", "my argument");

parsing of args is OK at the first function (e.g. if I cut & paste the
va_arg and printf part to the first function), but garbage is printed in
the second function. I'm surely missing something obvious, but I can't see
it.

Um, 'char*' and 'int' are different types?
(taking literally your remark about cut/paste)

int i;

/* ... */

i = va_arg(args, int);

cut/copy/paste is a double-edged sword. :)

-Mike
 
T

those who know me have no need of my name

in comp.lang.c i read:
int execute_command (char *name, ...)
{
va_list args;

va_start (args, name);
my_func (1, args);
va_end (args);
}

int my_func (int argc, ...)

args is a va_list, not a ..., so you cannot do this. make my_func's second
argument a va_list, drop the va_start and va_end, and use vprintf.
parsing of args is OK at the first function (e.g. if I cut & paste the
va_arg and printf part to the first function), but garbage is printed in
the second function.

didn't your compiler whine? if not you need to increase the warning level,
and if it did you needed to pay attention to what it said.
 

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,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top