如何用 C 语言编写运行时动态函数调用,使其在运行时接受可变数量的参数?
例如,考虑一下 long sum(int count, ...);
,它返回传递给它的(整数)参数值的总和。
$./a.out 1 2 3 4
10
$./a.out 1 2 3 4 -5
5
最佳答案
你就是不能。唉,您只能使用给定数量的参数来调用可变参数函数,而不能使用数组来调用。
根据架构的不同,您可以调用可变参数“后面”的函数 - 该函数采用 va_list
,前提是有一个,例如 vprintf()
“behind” printf()
- 带有数组的地址,但是这将是非常不可移植的。最好不要这样做。
最好是创建第三个函数,例如:
long asum(int count, long * arr)
{
long s = 0;
for (int i=0; i < count, i++) {
s += arr[i];
}
return s;
}
long vsum(int count, va_list ap)
{
long s = 0;
for (int i=0; i < count, i++) {
s += va_arg(ap, long);
}
return s;
}
long sum(int count, ...)
{
va_list ap;
va_start(ap, count);
long ret = vsum(count, ap);
va_end(ap);
return ret;
}
这个asum()
就是您要调用的。但这仅适用于将命令行参数转换为的中间数组。
也许额外的 ssum()
会有所帮助:
long ssum(int count, char ** arr)
{
long s = 0;
for (int i=0; i < count, i++) {
s += atol(arr[i]); // I am not sure if this is very portable; if not, choose another way.
}
return s;
}
关于c - 动态函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22281180/