dedsi
asked on
Writing functions with variable-length argument list
Im looking for a way to pass a variable-length argument list from one function to another.
Let me give an example. Consider the following function header:
void func(char *format, ...);
where "format" is a printf-like format string and the "..." is the argument list that corresponds to the "format" string (as in printf). Now, from this I want to be able to pass these arguments down to the printf/sprintf/fprintf functions. The function "func" would therefore look something like this:
void func(char *format, ...)
{
// second argument to printf should be the
// variable-length argument list sent to func
printf(format, [...]);
}
I think Ive understood how variable-length argument lists works, but I have not managed to get this to work. My question is therefore: Is this possible? If it is possible, how do I do it?
Thanks,
dedsi
Let me give an example. Consider the following function header:
void func(char *format, ...);
where "format" is a printf-like format string and the "..." is the argument list that corresponds to the "format" string (as in printf). Now, from this I want to be able to pass these arguments down to the printf/sprintf/fprintf functions. The function "func" would therefore look something like this:
void func(char *format, ...)
{
// second argument to printf should be the
// variable-length argument list sent to func
printf(format, [...]);
}
I think Ive understood how variable-length argument lists works, but I have not managed to get this to work. My question is therefore: Is this possible? If it is possible, how do I do it?
Thanks,
dedsi
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
thienpnguyen,
thank you for the quick reply, your solution works perfectly.
thank you for the quick reply, your solution works perfectly.
You should use stdarg.h library.
In it are some macros, etc .... to help.
Eg.
#include <stdarg.h>
double average(int i, ...) {
double total = 0;
int j:
va_list li;
va_start(li, i);
for (j = 1; j <= i; j++) {
total = total + va_arg(li, double);
}
va_end(li);
return total / i;
}
Cheers,
Keenez