TITLE: Handling variable argument lists


PROBLEM: Kevin Collins <kevinc@hppcih58.hp.com>

Can someone send me an example of the usage of ellipses in a
program.  I know how it looks in the signature but how do you
process the unknown number of parameters that may be passed in.


RESPONSE: jamshid@ses.com (Jamshid Afshar), 18 Jul 94

There is an excellent discussion of variable length argument lists,
with examples, in Steve Summit's (C) comp.lang.c Frequently Asked
Questions List.  Here's an excerpt.  FAQs are posted monthly and
available anytime via anonymous ftp at rtfm.mit.edu in pub/usenet.
Btw, using ellipses is not typesafe and is not useful for passing most
class objects.

------

Section 7. Variable-Length Argument Lists

7.1:	How can I write a function that takes a variable number of
	arguments?

A:	Use the <stdarg.h> header (or, if you must, the older
	<varargs.h>).

	Here is a function which concatenates an arbitrary number of
	strings into malloc'ed memory:

		#include <stdlib.h>		/* for malloc, NULL, size_t */
		#include <stdarg.h>		/* for va_ stuff */
		#include <string.h>		/* for strcat et al */

		char *vstrcat(char *first, ...)
		{
			size_t len = 0;
			char *retbuf;
			va_list argp;
			char *p;

			if(first == NULL)
				return NULL;

			len = strlen(first);

			va_start(argp, first);

			while((p = va_arg(argp, char *)) != NULL)
				len += strlen(p);

			va_end(argp);

			retbuf = malloc(len + 1);	/* +1 for trailing \0 */

			if(retbuf == NULL)
				return NULL;		/* error */

			(void)strcpy(retbuf, first);

			va_start(argp, first);

			while((p = va_arg(argp, char *)) != NULL)
				(void)strcat(retbuf, p);

			va_end(argp);

			return retbuf;
		}

	Usage is something like

		char *str = vstrcat("Hello, ", "world!", (char *)NULL);

