varargs...help appreciated

Kenstir kenc at madmax.Viewlogic.COM
Sat Nov 3 09:06:14 AEST 1990


Can you argument lists two levels down?  I passed an argument list
to a function, took a couple of parameters off, then tried to pass
the rest of the argument list down to another function.  At this
point, the parameters are no good.  Yet, it seems to work with vprintf
and the like.  Some code follows (sorry, this is as short as I could
get it).

Why do the first three calls to getMsg() work,
while the calls to err() fail?

Thanks!

/**************************************************************************/

#include <stdio.h>
#include <varargs.h>

#define SIZE 512

char *msg_array[] = {
    "This is message #1, int=%d, string=%s",
    "msg two, only a float=%f",
    "third one, string=%s, int=%d, long=%ld",
};
static char message[SIZE];

/**************************************************************************/

char *getMsg (va_alist)
    va_dcl /* msg_id, ... */
{
    va_list args;
    int msg_id;

    va_start (args);
    msg_id = va_arg (args, int);

    vsprintf (message, msg_array[msg_id], args);
    va_end (args);

    return (message);
}

/**************************************************************************/

void err(va_alist)
    va_dcl /* app, msg_num, ... */
{
    va_list args;
    char *cp, *ret, *app;
    int num;

    va_start (args);
    app = va_arg (args, char *);

    num = va_arg (args, int);
    ret = getMsg (num, args);

    va_end (args);

    printf ("%s: %s\n", app, ret);
}

/**************************************************************************/

main () {
    printf ("%s\n", getMsg(0, 37, "this is the string"));
    printf ("%s\n", getMsg(1, 37.37));
    printf ("%s\n", getMsg(2, "foo", 37, 37L));

    err ("app1", 0, 37, "this is the string");
    err ("app2", 1, 37.37);
    err ("app3", 2, "foo", 37, 37L);
}

/**************************************************************************/

p.s.  Anyone got any varargs macros, portable between
      traditional varargs and ANSI stdarg?
      Wanna share them?

p.p.s.  Thanks for helping!
--
Kenneth H. Cox
Viewlogic Systems, Inc.
kenstir at viewlogic.com
...!harvard!cg-atla!viewlog!kenstir



More information about the Comp.lang.c mailing list