如何将数组作为参数传递给vararg函数?

时间:2013-02-05 11:00:17

标签: c variadic-functions

我有一些看起来像这样的代码:

uint8_t activities[8];
uint8_t numActivities = 0;
...
activities[numActivities++] = someValue;
...
activities[numActivities++] = someOtherValue;
...
switch (numActivities)
{
   0 : break;
   1 : LogEvent(1, activities[0]);  break;
   2 : LogEvent(1, activities[0], activities[1]);  break;
   3 : LogEvent(1, activities[0], activities[1], activities[2]);  break;
   // and so on
}

其中LogEvent()是一个varargs函数。

有更好的方式来做到这一点吗?


[更新] Aplogies @ @ 0x69等。我没有说,有很多情况下LogEvent()无法将数组作为参数。遗憾。

2 个答案:

答案 0 :(得分:4)

没有标准方法来构造或操纵va_args个参数,甚至将它们传递给另一个函数(Standard way to manipulate variadic arguments?C Programming: Forward variable argument list)。您最好不要查看是否可以访问LogEvent的内部例程。

答案 1 :(得分:2)

将指针传递给int数组和多个int而不是

#include <stdio.h>

void logevent(int n, int num, int *l) {
    int i;
    for (i=0; i<num; i++) {
        printf("%d %d\n",n,*(l++));
    }
    }

int main() {

    int activities[8];
    activities[0]=2;
    activities[1]=3;
    activities[2]=4;
    int num=3;
    int n=1;
    logevent(n,num, activities);
    printf("=========\n");
    n=2;
    activities[3]=5;
    num=4;
    logevent(n,num, activities);

}