如何将变量参数传递给接受变量参数的函数?

时间:2022-08-20 18:02:52

There's a function avg(int, ...) which calculates the average number of input integers,

有一个函数avg(int,...),它计算输入整数的平均数,

avg(1,2,3) = 2, avg(2,3,4,5,6) = 4  

Now I have an array of integers that need to use avg() to get their average value,
but the array's size is dynamic, maybe read from stdin or from a file.

现在我有一个整数数组需要使用avg()来获取它们的平均值,但是数组的大小是动态的,可以从stdin或文件中读取。

Code example:

int i, num;  
scanf("%d", &num);  
int *p = malloc(num * sizeof(int));  
for(i = 0; i < num; ++i)  
    scanf("%d", &p[i]);  
// what should I do now?  
// avg(p[0], p[1],....)  

Note that the avg() function should be called only once.

请注意,avg()函数只应调用一次。

-- EDITED --
The avg() function is just an example, the real function is more complex than that.

- EDITED - avg()函数只是一个例子,真正的函数比这更复杂。

2 个解决方案

#1


4  

There's no portable way to do this. Most of the time when a varargs function exists, there is also a variant which directly accepts an array parameter instead.

没有可移植的方法来做到这一点。大多数情况下,当存在varargs函数时,还有一个直接接受数组参数的变体。

#2


0  

Just pass the p and the number of elements that p can point to.

只需传递p和p可以指向的元素数量。

float computeAverage( int *p, int count ) ; // count being `num` in this case.

In the function, have a loop that iterates 0 to count-1 and in which sum of all the elements can be computed. After the loop, just return sum/count which is the average.

在函数中,有一个迭代0到count-1的循环,并且可以计算所有元素的总和。循环之后,只返回总和/计数即平均值。

#1


4  

There's no portable way to do this. Most of the time when a varargs function exists, there is also a variant which directly accepts an array parameter instead.

没有可移植的方法来做到这一点。大多数情况下,当存在varargs函数时,还有一个直接接受数组参数的变体。

#2


0  

Just pass the p and the number of elements that p can point to.

只需传递p和p可以指向的元素数量。

float computeAverage( int *p, int count ) ; // count being `num` in this case.

In the function, have a loop that iterates 0 to count-1 and in which sum of all the elements can be computed. After the loop, just return sum/count which is the average.

在函数中,有一个迭代0到count-1的循环,并且可以计算所有元素的总和。循环之后,只返回总和/计数即平均值。