Link to home
Start Free TrialLog in
Avatar of gandalf79
gandalf79

asked on

va_arg problem

I am trying to create a function with a variable argument list. But, the code I have written (see below) is not giving me the first argument of the variable argument list.

The output to the program should be:

1
2
3

but I am getting

2
3
0

where the last value is out of bounds for the ap pointer. I used gcc 4.3.2 and intel ia32 11.0 compilers on Mac OS X 10.5.6, and got the same results on both.

I found that if I add the following line before the first call to va_arg() that I will get the correct output:

ap -= sizeof(size_t);

but I should not need to manually change the pointer before using it.

What am I doing wrong and how can I fix it?

Thank you in advance.
#include <iostream>
#include <stdarg.h>
 
void vatest(const unsigned int n, const size_t args, ...) {
  size_t x;
  va_list ap;
  va_start(ap, args);
 
//  ap -= sizeof(size_t); // I should not need this line!
  for(unsigned int i = 0; i < n; ++i) {
    x = va_arg(ap, size_t);
    std::cout << x << std::endl;
  }
 
  va_end(ap);
}
 
int main() {
  vatest(3, 1, 2, 3);
  return 0;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of wellhole
wellhole

You're passing the parameters wrong. Get rid of argument args and use n as the size for va_start.
Avatar of gandalf79

ASKER

Thanks for the quick response. I made the following changes and it work perfectly now.

void vatest(const unsigned int n, ...) {
  // ...
  va_start(ap, n);
Um, may I ask what was wrong with my - a bit more complete - answer?
I am sorry, I accidentally over looked your solution. When I looked at it, I thought your code was my code. I will attempt to rectify the situation.
Please, I am looking but I don't see how I can modify the accepted answer. =(

Had I not overlooked your solution, I would have given you credit for the question since yours is more complete. Thank you for your understanding.
Thank you for your help and the quick response.