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

Recommended Answers

All 2 Replies

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);

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

Thanks,

Dave

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.