gpt4 book ai didi

C - 在可变函数中将多个函数地址作为参数传递

转载 作者:太空狗 更新时间:2023-10-29 15:32:08 24 4
gpt4 key购买 nike

我正在尝试编写一个函数,它将采用前 n 个整数和可变数量的函数,并构建一个表,该表的第一列中的数字为“i”,其他列中的数字为“function(i)” .

但我似乎无法将我的函数地址传递给表生成器,因为我遇到了访问冲突错误。我做错了什么?

#include <stdio.h>
#include <math.h>
#include <stdarg.h>

typedef float(*f)(float);

// Some examples of f-type functions.
float square(float x) { return x*x; };
float root(float x) { return sqrt(x); };
float timesPi(float x) { return x * 3.14; };

// Display a table with first colon being the numbers from 1 to n,
// then the other columns to be f(i)
void table(unsigned int n, unsigned int nr_functions, ...)
{
va_list func;
va_start(func, nr_functions);

for (float i = 1; i <= n; i += 1)
{
printf("\n%6.0f |", i);
for (unsigned int j = 0; j < nr_functions; j++)
{
f foo = va_arg(func, f);
printf("%6.3f |", foo(i));
}
va_end(func);
}
}

// Main function
int main()
{
table(5, 3, &square, &root, &timesPi);
system("pause");
return 0;
}

对于上面的例子

table(5, 3, &square, &root, &timesPi);

我想回去

1   |   1.000 |  3.140 |
2 | 1.141 | 6.280 |
3 | 1.732 | 9.420 |
4 | 2.000 | 12.560 |
5 | 2.236 | 15.700 |

最佳答案

您需要重用参数列表的变量部分,这意味着您需要在正确的位置使用 va_start()va_end() — 在外循环内:

void table(unsigned int n, unsigned int nr_functions, ...)
{
for (unsigned int i = 1; i <= n; i++)
{
va_list func;
printf("\n%6.0f |", (double)i);
va_start(func, nr_functions);
for (unsigned int j = 0; j < nr_functions; j++)
{
f foo = va_arg(func, f);
printf("%6.3f |", foo(i));
}
va_end(func);
}
}

否则,除非您在循环内调用了 va_end(),否则您将离开列表的末尾,导致天知道会造成什么损害。

请注意,循环应该使用整数运算——随之而来的是对 printf() 的更改——这里我转换了值,但是将格式更改为 %6d 会也要保持理智(事实上可能更好)。

使用这个函数,我得到了输出:

 1 | 1.000 | 1.000 | 3.140 |
2 | 4.000 | 1.414 | 6.280 |
3 | 9.000 | 1.732 | 9.420 |
4 |16.000 | 2.000 |12.560 |
5 |25.000 | 2.236 |15.700 |

关于C - 在可变函数中将多个函数地址作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34362543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com