开发者

How to pass variable parameters to a function which accepts variable parameters?

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

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.

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.

-- EDITED --

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


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.


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜