如何在C中向变元函数传递和访问结构



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

以下是的示例情况

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

如何访问我通过的结构参数的内容

代码错误地使用了va_arg。使用它为变量分配可变参数,然后访问成员。

number n;
for (j = 0; j < count; j++) {
n = va_arg(ap, number);
if(n.dontIncludeFlag)
sum += va_arg(ap.num, number);
}

我想这就是您想要的:

#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
typedef struct s_number {
int num;
bool dontIncludeFlag;
} number_t;

float average(unsigned int count, ...)
{
int j = 0;
va_list ap;
float sum = 0;
number_t tmp;                   // This element will be our portal to access both
// `.num` and `.dontIncludeFlag` properties.
va_start(ap, count); 
for (j = 0; j < count; j++) {
tmp = va_arg(ap, number_t); // Pops out the element
if (tmp.dontIncludeFlag)    // Now able to access to the .dontIncludeFlag property
sum += tmp.num;         // Now able to access to the .num property
}
va_end(ap);
return sum / count;
}
int main(void)
{
number_t a = { .num = 5, .dontIncludeFlag = 0 };
number_t b = { .num = 2, .dontIncludeFlag = 1 };
number_t c = { .num = 1, .dontIncludeFlag = 0 };
float result = average(3, a, b, c);
printf("Average : %fn", result);
return 0;
}

别忘了包含必需的库,在编译时应该有一些警告,这可能会导致你只需添加一些包含就可以找到答案,然后你必须找到更深入的解决方案,因为会出现新的错误。

我最近遇到了同样的问题,并设法用inline function解决了它(在用NULL marker玩了很多var_argpointersmemory addresses甚至pre-processor sentinel macros之后(。jfjlaros和J-M-L的帮助来自deArduino community的Jackson对实现这一点至关重要(在我看来,非常清楚且易于处理(:

struct CIRCLE
{
String name;
double x;
double y;
int radius;
};
inline String drawCircle() {
return "";
}
template <class... Circles>
String drawCircle(CIRCLE& c, Circles&... cs) {
return c.name +','+ c.x +','+ c.y +','+ c.radius +';' + drawCircle(cs...);
}
void foo() {
CIRCLE circle1 = {"circle1", 48.4, 7.14, 1};
CIRCLE circle2 = {"circle2", 58.4, 17.14, 2};
CIRCLE circle3 = {"circle3", 68.4, 27.14, 3};
String str = drawCircle(circle1, circle2, circle3);  
printf("Test1: %sn", str); // will normally never work, except some times "per chance"
printf("Test2: %sn", str.c_str()); // '%s' is for a c-string not a String instance, therefore have to use 'str.c_str()' or change 'String str = "xxx"' to 'const char * s = "xxx"'
}

相关内容

  • 没有找到相关文章

最新更新