I am trying to get a variable number of arguments in one function, and pass them to another function. I tried this:

#include <iostream>
#include <stdarg.h>

void Function1(unsigned int num, ...);
void Function2(unsigned int num, va_list ap);

int main(int argc, char *argv[])
{
  Function1(3, 1, 2, 3);
  return 0;
}

void Function1(unsigned int num, ...)
{
  va_list ap;

  va_start(ap, num);

  Function2(num, ap);

}

void Function2(unsigned int num, va_list ap)
{
  for (unsigned int i = 0; i < num; i++)
    {
    double val = va_arg(ap,double);
    //printf ("\t%.2f",val);
    std::cout << "Val " << i << " : " << val << std::endl;
    }
    
  va_end(ap);

}

but the output is junk values.

Can anyone see what I've done wrong here?

Thanks,

Dave

main() is passing integers, but the va on line 27 is trying to get floats. Change main() to pass floats. Function1(3, 1.0F, 2.0F, 3.0F);

Edited 6 Years Ago by Ancient Dragon: n/a

Wow, I thought that was a reasonable cast to expect automatically. You're right though, it worked.

Thanks,

Dave

This article has been dead for over six months. Start a new discussion instead.