如何将结构传递和访问 C 中的可变参数函数 [英] how to pass and access a struct to a variadic function in C

查看:26
本文介绍了如何将结构传递和访问 C 中的可变参数函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想将结构传递给可变参数函数,并在 C 中使用所述结构内的值.我不知道如何访问传递的每个结构的内容.

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.

这是一个示例情况

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

推荐答案

您未正确使用 va_arg.使用它为变量分配一个可变参数,然后然后访问该成员.

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

这篇关于如何将结构传递和访问 C 中的可变参数函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆