I am trying to write a function that will take the first n integers and a variable number of functions and build a table with number "i" in the first column and "function (i)" in others.
But I, it seems, can not pass the addresses of my functions to the table generator, because I get an access violation error. What have I done wrong?
#include <stdio.h>
#include <math.h>
#include <stdarg.h>
typedef float(*f)(float);
float square(float x) { return x*x; };
float root(float x) { return sqrt(x); };
float timesPi(float x) { return x * 3.14; };
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);
}
}
int main()
{
table(5, 3, &square, &root, ×Pi);
system("pause");
return 0;
}
In the example above
table(5, 3, &square, &root, ×Pi);
I want to return
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 |
source
share