Path: utzoo!utgpu!water!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!bloom-beacon!bu-cs!purdue!decwrl!sun!pitstop!sundc!seismo!uunet!mcvax!enea!kth!draken!liuida!mikpe From: mikpe@mina.liu.se (Mikael Pettersson) Newsgroups: comp.lang.c Subject: Re: Can ANYONE tell me why this code snippet doesn't work?? Summary: man 3 varargs Keywords: varargs Message-ID: <982@mina.liu.se> Date: 18 Oct 88 17:08:57 GMT References: <7778@gryphon.CTS.COM> <315@uplog.se> Organization: CIS Dept, Univ of Linkoping, Sweden Lines: 57 In article <7778@gryphon.CTS.COM> rickf@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 #include 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@uplog.se> thomas@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 ) 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@ida.liu.se Dept of Comp & Info Science ! UUCP: mpe@liuida.uucp -or- University of Linkoping ! {mcvax,munnari,uunet}!enea!liuida!mpe Sweden ! ARPA: mpe%ida.liu.se@uunet.uu.net