views:

72

answers:

4

I have a function

void func(int x, char *str, ...)
{
  ...
}

I am invoking it as follows:

func(1, "1", "2", "3");

How can I print the values of all the extra arguments (2, 3) in function?

A: 

Hello, lookup va_list in this site. Example: http://stackoverflow.com/questions/3792761/what-is-ellipsis-operator-in-c/3792768#3792768

Benoit
You linked to your own answer to a closed question, which consists of nothing but a link to a blog I've never heard of.
reemrevnivek
@reemrevnivek. now you've heard of it.
aaronasterling
and? what if the article is interesting and other answers to that question are interesting too?
Benoit
A: 

you can use it

mr. Vachovsky
+1  A: 

From the man page of STDARG about the use of va_arg to get the next argument:

If there is no next argument, or if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), random errors will occur.

Hence, unless you want random errors to creep in, you should know the number of arguments beforehand.

Even so, if you want to throw caution to the winds, you could try:

void func(int x,char *str, ...)
{
    va_list al;
    va_start(al,str);

    while(x>0)
    {
        str=va_arg(al,char *);
        --x;      
    }

    while(str != NULL)
    {
        printf("%s ",str);
        str=va_arg(al,char *);
    }
    va_end(al);
}

With,

func(1,"1","2","3");

I got the output,

2 3 U��WVS�O  

If it satisfies your purpose, you could pick out the required number of arguments from this output.

Kedar Soparkar
+1  A: 

It is customary with variable arguments to pass a string which describes the variable arguments, e.g. printf( char *format_string, ... );

This is a solution - and the customary solution - to your problem.

Pass an additional argument which describes the variable arguments, and then use that information to process the variable arguments.

So, if you receive a printf-like format string and it is "%d%u", you know you have an int, followed by an unsigned int.

Blank Xavier