Can ANYONE tell me why this code snippet doesn't work??

Mikael Pettersson mikpe at mina.liu.se
Wed Oct 19 03:08:57 AEST 1988


In article <7778 at gryphon.CTS.COM> rickf at pnet02.cts.com (Rick Flower) writes:
>I've been trying to get the following code to work..
> [Rick wants to write his own printf(3s) clone]
> [buggy def of Test() omitted]
>main()
>{
>        Test("%d %d %d %d",10,20,30,40);
>}

The answer to your problem is simple: use varargs().
With varargs, you can either parse the format string just like printf(3s)
does, or you can be a little lazy and let vsprintf(3s) do the formatting
for you before sending the result to whoever wants it. I'll give you an
example:
---snip-snip-snip---
#include <stdio.h>
#include <varargs.h>

void Test(va_alist)
va_dcl					/* n.b. NO ; */
{
	va_list ap;
	char *fmt, buf[BUFSIZ];

	va_start(ap);			/* init */
	fmt = va_arg(ap, char *);	/* get 1st arg: a char * */
	vsprintf(buf, fmt, ap);		/* do the formatting */
	fputs(buf, stdio);		/* dump it on stdout */
	va_end(ap);			/* cleanup */
}
---snip-snip-snip---

Check the man pages for more detail. Any decent C book (like H&S-2) will
probably also have some examples.

In <315 at uplog.se> thomas at uplog.UUCP (Thomas Hameenaho) responds:
>The problem is that the stack doesn't look the way you would expect on entry
>to sprintf().
>
> [ lots of machine AND compiler specific detail omitted ]
>...
>If you want to do something like what I think you are aiming at you have to
>do it some other way. Possibly manipulating the stackpointer in assembler!

Noooo!
The great advantage in using varargs(3) is PORTABILITY. It's guaranteed
to work in any conforming ANSI C implementation (where it's called <stdarg.h>)
and it will work in virtually all existing UNIX C compilers as well.
Assumptions about stack layout, parameter passing and order of evaluation
will only lead to bugprone and non-portable code.

/Mike
-- 
Mikael Pettersson           ! Internet:mpe at ida.liu.se
Dept of Comp & Info Science ! UUCP:    mpe at liuida.uucp  -or-
University of Linkoping     !          {mcvax,munnari,uunet}!enea!liuida!mpe
Sweden                      ! ARPA:    mpe%ida.liu.se at uunet.uu.net



More information about the Comp.lang.c mailing list