如何将可变参数传递给接受可变参数的函数?
有一个函数 avg(int, ...)
计算输入整数的平均数量,
avg(1,2,3) = 2, avg(2,3,4,5,6) = 4
现在我有一个整数数组,需要使用 avg()
来获取他们的平均值,
但数组的大小是动态的,可以从 stdin 或文件中读取。
代码示例:
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],....)
请注意,avg()
函数只能调用一次。
-- 已编辑 --
avg() 函数只是一个示例,实际函数比这更复杂。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
没有可移植的方法可以做到这一点。大多数情况下,当存在 varargs 函数时,还有一个直接接受数组参数的变体。
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.
只需传递
p
和p
可以指向的元素数量。在该函数中,有一个迭代0 到 count-1 的循环,并且可以在其中计算所有元素的总和。循环结束后,只需返回
sum/count
这是平均值。Just pass the
p
and the number of elements thatp
can point to.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.