1

Hello i would like to pass a struct to a variadic functions and use values inside the said struct in C. What i do not know how to do is how to access the contents of each struct that is passed.

Here is a example situation

typedef struct  {
 int num;
 bool dontIncludeFlag;
} number;


int average(unsigned count, ...){
    va_list ap;
    int j;
    int sum = 0;

    va_start(ap, count); 
    for (j = 0; j < count; j++) {
        if(va_arg(ap,number.dontIncludeFlag))        //This line does not work
        sum += va_arg(ap.num, number);               //so does this line
    }
    va_end(ap);

    return sum / count;
}


int main(){

   number a,b,c;

   a.num= 5;
   a.dontIncludeFlag = 0;

   b.num= 2;
   b.dontIncludeFlag= 1;

   c.num= 1;
   c.dontIncludeFlag= 0;

   average(3,a,b,c);
}

How do i access the contents of the struct arguments i passed

Jake quin
  • 661
  • 1
  • 4
  • 20
  • 2
    There must be quite a few online-tutorials on how to use variadic function all over the Internet. All of them should point out that the `va_arg` "function" (it's really a macro) will take a *type* as argument, and it get the next *whole* argument. You can't use `va_arg` to get part of an argument (like parts of a structure). – Some programmer dude Apr 03 '21 at 15:54
  • Does this answer your question? [An example of use of varargs in C](https://stackoverflow.com/questions/15784729/an-example-of-use-of-varargs-in-c) – Nikos Athanasiou Apr 03 '21 at 16:00
  • 1
    @Someprogrammerdude you actually led me to solve the problem, sadly the one i was reading did not mention any of that. so how i solved it is inside the for loop i created a temp struct variable `number temp = va_arg(ap,number)` and from there its walk in the park , replace the two problematic line with `if(temp.dontIncludeFlag == 0)` and `sum+= temp.num;`. If you want to post an answer good sir, ill accept it so that you can take the points – Jake quin Apr 03 '21 at 16:08
  • @NikosAthanasiou actually it does not, my problem is accessing the struct that was passed inside the variadic function. Some programmer dude actually gave me the necessary information to solve the problem – Jake quin Apr 03 '21 at 16:13

1 Answers1

2

You're using va_arg incorrectly. Use it to assign a variadic argument to a variable, and then access the member.

    number n;
    for (j = 0; j < count; j++) {
        n = va_arg(ap, number);
        if(n.dontIncludeFlag)
            sum += va_arg(ap.num, number);
    }
Samuel Hunter
  • 459
  • 2
  • 11