Jim C
Jim C

Reputation: 165

Passing variable numbers of arguments to a C function

I'm exploring using variable arguments in C, using GNU (inside Code::Blocks). When I execute the following code:

#include <stdio.h>
#include <stdarg.h>

void VarargsTest(int n_args, ...)
{
    int i, arg;
    va_list ap;

    fprintf(stderr, "N_args is %d\n", n_args);
    va_start(ap, n_args);
    for(i= 0; i < n_args; i++)
        {
        arg= va_arg(ap, int);
        fprintf(stderr, "arg %d is %d\n", i, arg);
        }
    va_end(ap);
}

int main()
{
    VarargsTest(1,2,3,4,5,6,5,4,3,2,1);
    return 0;
}

I get the following result:

N_args is 1
arg 0 is 2

i.e. the number of arguments (11) is not being reported correctly to the VarargsTest function, and even the one and only argument it's seeing isn't correct. Any ideas?

Upvotes: 1

Views: 91

Answers (2)

bznein
bznein

Reputation: 908

You have to explicitly pass the number of arguments to the function, so the line

VarargsTest(1,2,3,4,5,6,5,4,3,2,1);

should be

VarargsTest(11,1,2,3,4,5,6,5,4,3,2,1);

Upvotes: 3

dbush
dbush

Reputation: 223689

You function expects the first parameter passed to the function to be the number of variable arguments passed to the function. Since you're passing in 1 for this value, it's only looking at one parameter past the required one.

If you want it to read all parameters the first value should be 10, since you have one required parameter and 10 optional parameters.

Upvotes: 6

Related Questions