Jad*_*rma 5 c function-pointers variadic-functions memory-address
我正在尝试编写一个函数,该函数将采用前 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, ×Pi);
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
对于上面的例子
table(5, 3, &square, &root, ×Pi);
Run Code Online (Sandbox Code Playgroud)
我想回来
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 |
Run Code Online (Sandbox Code Playgroud)
您需要重用参数列表的变量部分,这意味着您需要va_start()和va_end()在外循环内的正确位置 \xe2\x80\x94 中
void table(unsigned int n, unsigned int nr_functions, ...)\n{\n for (unsigned int i = 1; i <= n; i++)\n {\n va_list func;\n printf("\\n%6.0f |", (double)i);\n va_start(func, nr_functions);\n for (unsigned int j = 0; j < nr_functions; j++)\n {\n f foo = va_arg(func, f);\n printf("%6.3f |", foo(i));\n }\n va_end(func);\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n否则,您将离开列表的末尾,除非您调用了va_end()在循环内调用,导致只有天知道会造成什么损害。
请注意,循环应使用整数算术 \xe2\x80\x94 ,并对printf()\xe2\x80\x94 进行相应更改,此处我转换了值,但将格式更改为%6d也是合理的(事实上可能更好)。
通过这个函数,我得到了输出:
\n\n 1 | 1.000 | 1.000 | 3.140 |\n 2 | 4.000 | 1.414 | 6.280 |\n 3 | 9.000 | 1.732 | 9.420 |\n 4 |16.000 | 2.000 |12.560 |\n 5 |25.000 | 2.236 |15.700 |\nRun Code Online (Sandbox Code Playgroud)\n