Here's my code, it is supposed to calculate the standard deviation of the randomly generated array that fillArray populates. stdDev is supposed to calculate the standard deviation. otherStats is supposed to find the largest and smallest value in the array. So far, the only thing that is being generated are 0s for the deviation, smallest, and largest. Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float fillArray (float array[7][5]);
float printArray (float array[7][5], float deviation, float largest, float smallest);
float stdDev (float array[7][5], float deviation, float average);
float otherStats (float array[7][5], float largest, float smallest);
int main ()
{
float deviation, average, largest, smallest;
float array[7][5];
fillArray (array);
stdDev (array, deviation, average);
otherStats (array, largest, smallest);
printArray (array, deviation, largest, smallest);
}
float fillArray (float array[7][5])
{
int row, column;
for (row = 0; row < 7; row++)
{
for (column = 0; column < 5; column++)
{
array[row][column] = (float) rand () / (float) RAND_MAX;
}
}
return array[7][5];
}
float stdDev (float array[7][5], float deviation, float average)
{
float number1, number2;
array[7][5] = fillArray(array);
int ROw, Col;
for (ROw = 0; ROw < 7; ROw++)
{
for (Col = 0; Col < 5; Col++)
{
number1 = array[ROw][Col] + number1;
average = number1 / 35;
}
}
for (ROw = 0; ROw < 7; ROw++)
{
for (Col = 0; Col < 5; Col++)
{
number2 = average - array[ROw][Col];
deviation = sqrt (number2 / 35);
}
}
return deviation;
}
float otherStats (float array[7][5], float largest, float smallest)
{
array[7][5] = fillArray(array);
float num1, num2; //Check which ones largest or smallest.
int ROW, COLUMN;
for (ROW = 0; ROW < 7; ROW++)
{
for (COLUMN = 0; COLUMN < 5; COLUMN++)
{
num1 = array[ROW][COLUMN];
num2 = array[1][1];
largest = num2;
smallest = num1;
if (num1 > num2)
{
largest = num1;
}
else
{
smallest = num1;
}
}
}
return largest, smallest;
}
float printArray (float array[7][5], float deviation, float largest, float
smallest)
{
int Row, Column;
printf("Column #: ");
for (Column = 0; Column < 5; Column++)
{
printf ("%d ", Column);
}
printf("\nRow #|________________________________\n");
for (Row = 0; Row < 7; Row++)
{
printf("%d | ", Row);
for (Column = 0; Column < 5; Column++)
{
printf ("%4.2f ", array[Row][Column]);
}
printf ("\n");
}
printf("The standard deviation is %f, the largest is %f, the smallest is %f.\n",
deviation, largest, smallest);
}
Any help to figure out my error would be super appreciate. It compiles fine, it's just that my logic or something is messed up.
Thanks in advance.
This is the output:
Column #: 0 1 2 3 4
Row #|________________________________
0 | 0.53 0.04 0.44 0.93 0.93
1 | 0.72 0.28 0.74 0.64 0.35
2 | 0.69 0.17 0.44 0.88 0.83
3 | 0.33 0.23 0.89 0.35 0.69
4 | 0.96 0.59 0.66 0.86 0.44
5 | 0.92 0.40 0.81 0.68 0.91
6 | 0.48 0.22 0.95 0.92 0.15
The standard deviation is -0.000000, the largest is 0.000000, the smallest is 0.000000.
This is not the answer to your coding woes, but it is an example of what you're doing wrong. I certainly won't expect this to garner much attention (besides maybe a few down votes and some sharp criticisms).
C is a pass-by-value language. Though not easily grasped by most that experience it, this includes everything, (arrays not withstanding, but even those are if you apply the term "value" correctly).
Example #1: Value Parameters
This trivial example is to demonstrate that the address of the passed parameters to a function are not the same as the address of the arguments supplied to the function.
#include <stdio.h>
int foo_one(int a, int b)
{
printf("foo: &a = %p, &b=%p\n", &a, &b);
return a+b;
}
int main()
{
int a = 1, b = 2;
printf("main: &a = %p, &b=%p\n", &a, &b);
foo_one(a,b);
return 0;
}
Output (address values will vary on your system)
main: &a = 0x7fff5fbff938, &b=0x7fff5fbff934
foo: &a = 0x7fff5fbff90c, &b=0x7fff5fbff908
Note the logical address of the variables in the function are different than those in main(). The values of a and b are pushed into temporary storage (commonly a "stack", but you likely don't know what that is without a formal data-structures course, and if you had one of those under your belt you probably would not be asking this question). Then the function call is made.
Example #2: Dysfunctional Out-Parameter
So why do you care. Well, now consider this:
#include <stdio.h>
void foo_two(int a, int b, int c)
{
printf("foo: &a = %p, &b=%p, &c=%p\n", &a, &b, &c);
c = a + b;
}
int main()
{
int a = 1, b = 2, c = 0;
printf("main: &a = %p, &b=%p, &c=%p\n", &a, &b, &c);
foo_two(a,b,c);
printf("c = %d\n", c);
return 0;
}
Output (address values will vary on your system)
main: &a = 0x7fff5fbff938, &b=0x7fff5fbff934, &c=0x7fff5fbff930
foo: &a = 0x7fff5fbff90c, &b=0x7fff5fbff908, &c=0x7fff5fbff904
c = 0
What just happened? The c variable we modified in foo_two() was not the variable in main(). They have different memory addresses. The one we modified in foo_two() was a by-value copy (a "temp" variable discussed in Example #1).
Example #3: Functional Out-Parameter
If only there was a way we could tell foo_three() the memory address of the variable in main() directly... Somehow pass that address as the "value" for the parameter, then use it to store our result where it needs to go; in main::c.
This is exactly what pointers do. In C, a pointer is a variable that holds an address to some other data of a specific type. Where an int holds an integer value, a int* holds an address where an int can be found.
#include <stdio.h>
void foo_three(int a, int b, int* ptr)
{
printf("foo: &a = %p, &b=%p, ptr=%p\n", &a, &b, ptr);
*ptr = a + b; // note the dereference operator
}
int main()
{
int a = 1, b = 2, c = 0;
printf("main: &a = %p, &b=%p, &c=%p\n", &a, &b, &c);
foo_three(a,b,&c); // note the address of c being passed
printf("c = %d\n", c);
return 0;
}
Output (address values will vary on your system)
main: &a = 0x7fff5fbff938, &b=0x7fff5fbff934, &c=0x7fff5fbff930
foo: &a = 0x7fff5fbff90c, &b=0x7fff5fbff908, ptr=0x7fff5fbff930
c = 3
This is important. Look carefully at what is being printed in foo_three(). The value of the ptr parameter, a pointer, is the same as the address of the c variable in main() this gives us the ability to modify the int at that address directly.
Summary
If you want to pass something by address in C, then passing the address is exactly what you have to do; pass the address and declare the parameter to be a pointer to the variable type. Use the dereference operator to write/read data to/from said address while in the function, and the caller-side variable will be appropriately modified.
Now after all that, look back at your program and see if you can understand how this can be applied to your problem(s). And study C pointers. They're not magic, and they are heavily used in most C programs. It's worth the time to learn as soon as possible.
I presume you're a student. When learning a new language, it really helps to read other people's code. I rewrote your mean / standard deviation function, showing how I approach this kind of thing. (1-dimensional not 2-dimensional... no free lunch!)
Hope this gets you on the right track.
I do agree with the other posters that you need to get comfortable using the debugger... even if there are no compiler errors or linker errors, the program still may not work correctly. You can validate the correctness of a function by using a unit test framework such as Google Test or CppUnit, or you can just use an ad hoc test function as I show below.
// tested with minGW_w32 gcc-4.7.2
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/// Calculate mean and standard deviation of a 1-dimensional array.
/// Example showing how to pass values by reference.
///
/// #param[in] x = 1-dimensional array of values to evaluate
/// #param[in] length = number of elements in array
/// #param[out] pdMean = caller-allocated storage for arithmetic mean average
/// #param[out] pdStdDev = caller-allocated storage for standard deviation
///
/// void return type because this function does not have a return value.
///
void calculateMeanAndStdDev (double x[], size_t length, double* pdStdDev, double* pdMean)
{
size_t index; // size_t is an unsigned integer type useful for counting array elements
double sumX = 0;
double sumXSquared = 0;
for (index = 0; index < length; index++)
{
// accumulate sum of the x values
sumX += x[index];
// accumulate the sum of each x squared
sumXSquared += ( x[index] * x[index] );
}
// pdMean is a pointer to the variable in the caller, which will receive the value
// *pdMean is the object that double& pdMean points to.
// I'm using the pd prefix to mean pointer to double.
// I prefer to write this as (*pdMean) to help clarify that I'm using * to dereference a pointer, not to perform multiplication.
(*pdMean) = sumX / length;
double variance = 0;
for (index = 0; index < length; index++)
{
const double differenceFromMean = x[index] - (*pdMean);
// without the parenthesis this is written as differenceFromMean = x[index] - *pdMean;
variance += differenceFromMean * differenceFromMean;
}
(*pdStdDev) = sqrt ( variance / length);
/// #note there's a more effient way to calculate mean and standard deviation, where you accumulate sumX and sumXSquared in a single pass,
/// then mean is sumX / length and StdDev is calculated from sumXsquared and (sumX)*(sumX).
/// For purposes of this exercise I stuck with the more direct equation.
}
/// Example ad hoc test driver calling calculateMeanAndStdDev()
void Test_calculateMeanAndStdDev()
{
double demoArray[] = { 1.0, 2.0, 3.0, 7.5, 9.2 };
const double expect_Mean = 4.54;
const double expect_StdDev = 3.2196894260161177;
double Mean; // will be filled in by calculateMeanAndStdDev
double StdDev; // will be filled in by calculateMeanAndStdDev
calculateMeanAndStdDev(demoArray, sizeof(demoArray)/sizeof(double), &StdDev, &Mean);
const double compare_threshold = 0.001;
if ( abs(Mean - expect_Mean) > compare_threshold ) {
printf("\n""Test_calculateMeanAndStdDev() fail: Mean=%1.6f buf expect_Mean=%1.6f", Mean, expect_Mean);
} else {
printf("\n""Test_calculateMeanAndStdDev(): Mean=%1.6f as expected", Mean);
}
if ( abs(StdDev - expect_StdDev) > compare_threshold ) {
printf("\n""Test_calculateMeanAndStdDev() fail: StdDev=%1.6f buf expect_StdDev=%1.6f", StdDev, expect_StdDev);
} else {
printf("\n""Test_calculateMeanAndStdDev(): StdDev=%1.6f as expected", StdDev);
}
}
int main(void)
{
Test_calculateMeanAndStdDev();
return 0;
}
C pointers are very powerful and fundamental to the language, but they're also one of the trickiest features to understand. That's why languages like Java hide this pointer mechanism from the programmer. In C you have to program defensively, because the compiler always assumes you know what you're doing. Want to write code that modifies itself during execution? C is ok with that, even if your program kills itself. Write outside the bounds of an array allocated on the stack? Sure, no problem, your function just won't be able to return... So all in all, when dealing with pointers, especially when first starting out, code defensively to try to avoid getting confused. Because you can't rely on compiler warnings to tell you if there's going to be a problem.
Related
There is a serie for the exp function whitch looks like this:
exp(x) = (x^0)/0! + (x^1)/1! + (x^2)/2! + (x^3)/3! + ···. And I'm trying to compute it for different values of x, checking my results with a calculator and I found that for big values, 20 for example, my results stop increasing and get stuck in a value that is almost the real one. I get 485165184.00 and the real value is 485165195.4.
I must do this code in a for cycle or a recursive function, since it is a homework assignment.
My code looks as following
#include <stdio.h>
#define N 13
#define xi 3
double fun7(int n, int m){
int i;
double res=1, aux=0;
for(i=1, aux=1; i<(n+1); i++){
res += aux;
aux *= m;
aux /= i;
}
return res-1;
}
int main() {
int a, b, pot, x[xi];
float R[N][xi];
x[0] = 5;
x[1] = 10;
x[2] = 20;
for(b=0; b<xi; b++){
for (a=0, pot=1; a<N; a++){
R[a][b] = fun7(pot, x[b]);
pot *= 2;
}
}
for(b=0; b<xi; b++){
for (a=0, pot=1; a<N; a++){
printf("%d\t%f\n", pot, R[a][b]);
pot *= 2;
}
printf("\n");
}
return 0;
}
The float data type can normally represent numbers with a tad more than 7 decimal digits of precision.
485165184 has 9 decimal digits. The last two digits are just meaningless noise as far as float goes. You really should be showing 4.851652e8, which is the correct value for exp(20) with the given level of precision.
If you want to increase precision, try using double or long double data types.
I am new to C and have a question about making a simple function in which I hand in a given array and also an integer that tells the number of numbers in that array. I wrote this code but I am unsure if it is correct. What I was trying to do was to make it so that I could find the product of all the numbers in the array.
#include <stdio.h>
#include <math.h>
double my_product (int n, double x[]);
int main (void)
{
my_product(n, x);
return 0;
}
double my_product (int n, double x[])
{
int i;
product=0;
for(i=0; i<n; i++)
{
product=x[i]*x[i+1]
}
return product;
}
I will comment your code, pointing out your mistakes:
double my_product (int n, double x[])
{
int i;
product=0;
/* The variable "product" needs to have a type.
In your case, since your values have type "double",
and a "double" return is expected,
of course you need to declare:
double product;
On the other hand,
it has not sense to initialize a product to 0,
since multiplication by 0 "kills" every value,
giving you a value 0, not matter what you do.
So, initialize in this way:
double product = 1.0;
*/
for(i=0; i<n; i++)
{
/* A semicolon is missing in the next line: */
product=x[i]*x[i+1]
/* In every step of the loop,
the variable "product" will hold the value
given by the multiplication of two consecutive values
in the array.
Thus, you lose every previous factor.
Also, when i == n you are in trouble,
because x[i] == x[n] is beyond the limits of the array,
which may cause access violation to memory.
You need a cumulative product.
Starting by the initialized value 1.0,
you have to multiply the previous value of "product"
with the present value of the array: x[i]
product = product * x[i];
Thus, in the step i, it can be proved that
the variable "product" contains the cumulative product
of the factors x[0], x[1], ... up to x[i].
A more compact notation in C can be provided by the *= operator:
product *= x[i];
*/
}
return product;
}
In the function main():
int main (void) {
my_product(n, x);
/* The function "my_product()" has been called with
undeclared parameters "n" and "x".
First, you have to declare and define the value of "n",
as much as the array "x", having type double:
double x[] = {3.0, 1.41, -2.3, 9.4, };
int n = sizeof(x)/sizeof(double);
The first line would declare an array "x" having type "double",
and initialized to hold 4 values, as it's seen there.
The second line would declare an "int" variable "n"
holding the number of elements in the array,
which can be computed as the size of x (measured in bytes)
divided by the size of the type "double"
(of course, in this example we have n == 4).
Finally, you need to do something with the result returned by
the function "my_product()".
If not, the returned value will be completely lost.
For example, to hold it in a variable, or to show it on screen.
double ans;
ans = my_product(n, x);
*/
return 0;
}
The code will look like this:
#include <stdio.h>
#include <math.h>
double my_product (int n, double x[]);
int main (void)
{
double x[] = {3.0, 1.41, -2.3, 9.4, };
int n = sizeof(x)/sizeof(double);
double ans;
ans = my_product(n, x);
printf("Product is: %f\n", ans);
return 0;
}
double my_product (int n, double x[])
{
product=1.0;
int i;
for(int i=0; i<n; i++)
{
product *= x[i];
}
return product;
}
In your function my_product you overwrite the value of product in the loop
for(i=0; i<n; i++)
{
product=x[i]*x[i+1]
}
So suppose your array x = {2, 3, 4}, then first product gets the value of 2*3, but then you overwrite it with the value of 3*4. What you probably want is to use a variable in which you accumulate the results of the multiplications (e.g. total = total * number).
Also, watch out with your indexing. In your current code i+1 can be larger than the number of elements in x, so you run out of the array.
I am trying to sort a 2d array based on a particular column using qsort in C. I am attaching a minimal working code I am using. Essentially I am passing the pointer to the rows of the array to qsort, and based on the column number I want to sort, I modify the element to compare inside the compare function. Now, according to C convention, if I have 2 columns, I expect colnum=0 and colnum=1 to correspond to columns 1 and 2. But, in my implementation, I get the correct result if colnum=1 means column 1 and colnum=2 means column 2. I am stumped as to why this should be ? (I have also included the array allocation function I use).
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "myfun.h"
static int colnum = 0;
int cmp(const void * a,const void * b);
int main(){
int i;
double **z1;
z1=matrix(5,2);
for (i=0; i<5; i++){
z1[i][1]=-i-1; z1[i][2]=16*i+10;
printf("before sort z1 %lf %lf \n",z1[i][1],z1[i][2]);
}
colnum=2;
qsort(z1,5,sizeof(double*),cmp);
for (i=0; i<5; i++){
printf("after sort z1 %lf %lf \n",z1[i][1],z1[i][2]);
}
getchar();
}
int cmp(const void * a,const void * b)
{
double** x = (double**) a;
double** y = (double**) b;
double xval, yval;
xval = *(*(x)+colnum);
yval = *(*(y)+colnum);
printf("%lf %lf \n",xval,yval);
if (xval < yval )
{
return 1;
}
else if (xval > yval)
{
return -1;
}
else
{
return 0;
}
}
double** matrix(int rows,int cols){
int k;
double **m;
m = (double **)malloc(rows * sizeof(double *));
for (k=0; k<rows; k++){
m[k] = (double *)malloc(cols * sizeof(double));
}
return m;
}
Your program has undefined behavior, because your are accessing memory beyond the boundary allocated by your inner allocation loop of matrix():
m = (double **) malloc(rows * sizeof(double *));
for (k = 0; k < rows; k++) {
m[k] = (double *) malloc(cols * sizeof(double));
}
Since cols has the value 2, malloc() only returns memory for 2 elements of type double. But, your code is initializing and reading a non-existing third element instead.
Since doing so is undefined, producing the output you expect is within the realm of possible behaviors. However, it is incorrect since you run the risk of corrupting the heap, and reading invalid data. Running your program under valgrind produces "Invalid write" and many "Invalid read" errors due to this problem in your program.
The correct approach is to store the values in their proper 0 and 1 column indexes in your initialization, set colnum to 1 to sort by the second column, and read from the proper 0 and 1 indexes when you print the array values.
z1 = matrix(5, 2);
for (i = 0; i < 5; i++) {
z1[i][0] = -i - 1;
z1[i][1] = 16 * i + 10;
printf("before sort z1 %lf %lf \n", z1[i][0], z1[i][1]);
}
colnum = 1;
qsort(z1, 5, sizeof(double *), cmp);
for (i = 0; i < 5; i++) {
printf("after sort z1 %lf %lf \n", z1[i][0], z1[i][1]);
}
As a side note, when I was formatting your code for this answer, I noticed that you used an old C anachronism, probably unintentionally:
z1[i][1]=-i-1; /*...*/
The =- construct was the original C's (pre C.89) way of spelling the -= operator. It is highly unlikely you will end up using a compiler that will honor that operator without a diagnostic, but you should be wary of this syntax, and separate the = and the - tokens to remove the ambiguity.
z1[i][1] = -i - 1; /*...*/
How do I write a function that have a input function (is objective to any function), array of input numbers and length of input array?
Function:
double accumulator(double (*function)(double, double), double array[], int length)
Main:
int main(){
double array[10];
for (int i=0; i<10; i++)
array[i] = i+1;
printf("Sum is: %g\n", accumulator(sum,array,10));
printf("Product is: %g\n", accumulator(product,array,10));
return 0;
}
For example sum should be 55 (1 + 2 + .... + 10) and product 362880 (1 * 2 * ... * 10).
I guess the function should by recursive but I still cant get the right results :/
I have got this non-recursive solution but it of course works only for sum...
double accumulator(double (*function)(double, double), double array[], int length)
{
int temp = 0;
for (int i = 0;i<length;i++)
{
temp = (*function)(temp, array[i]);
}
return temp;
}
on the top of course:
double sum(double x, double y){
return x+y;
}
double product(double x, double y){
return x*y;
}
What is wrong with:
double multiplicator(double (*function)(double, double), double array[], int length)
{
int temp = 1;
for (int i = 0;i<length;i++)
{
temp = (*function)(temp, array[i]);
}
return temp;
}
Either a different function or you need to supply the neutral element for the operation (0 for sum, 1 for product).
It doesn't work for multiplication because multiplying anything by 0 gives, well 0
you need to use first element as an initial value
double accumulator(double (*function)(double, double), double array[], int length)
{
int temp = array[0];
for (int i = 1; i < length;i++) // start from #1
{
temp = (*function)(temp, array[i]);
}
return temp;
}
Your solution is almost there if you set temp = array[0] and start your loop at i = 1 instead of i = 0.
Two thoughts:
You should use double temp rather than int temp.
You need to have a different starting value for addition versus multiplication. A sum should start at temp = 0, but a product should start at temp = 1. Otherwise the product will always be 0.
You could add add another initial value parameter:
double accumulator(double (*function)(double, double), double array[], int length, double initial)
Or you use the first array element as the starting value (but then you'll need to check for the special case where the array is empty):
double temp = array[0];
For what it's worth, your "accumulator" function is alternatively known as "reduce" in other functional programming contexts. That may help if you want to Google the term.
Little bit of a 2 parter. First of all im trying to do this in all c. First of all I'll go ahead and post my program
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
#include <string.h>
double f(double x);
void Trap(double a, double b, int n, double* integral_p);
int main(int argc, char* argv[]) {
double integral=0.0; //Integral Result
double a=6, b=10; //Left and Right Points
int n; //Number of Trapezoids (Higher=more accurate)
int degree;
if (argc != 3) {
printf("Error: Invalid Command Line arguements, format:./trapezoid N filename");
exit(0);
}
n = atoi(argv[2]);
FILE *fp = fopen( argv[1], "r" );
# pragma omp parallel
Trap(a, b, n, &integral);
printf("With n = %d trapezoids....\n", n);
printf("of the integral from %f to %f = %.15e\n",a, b, integral);
return 0;
}
double f(double x) {
double return_val;
return_val = pow(3.0*x,5)+pow(2.5*x,4)+pow(-1.5*x,3)+pow(0*x,2)+pow(1.7*x,1)+4;
return return_val;
}
void Trap(double a, double b, int n, double* integral_p) {
double h, x, my_integral;
double local_a, local_b;
int i, local_n;
int my_rank = omp_get_thread_num();
int thread_count = omp_get_num_threads();
h = (b-a)/n;
local_n = n/thread_count;
local_a = a + my_rank*local_n*h;
local_b = local_a + local_n*h;
my_integral = (f(local_a) + f(local_b))/2.0;
for (i = 1; i <= local_n-1; i++) {
x = local_a + i*h;
my_integral += f(x);
}
my_integral = my_integral*h;
# pragma omp critical
*integral_p += my_integral;
}
As you can see, it calculates trapezoidal rule given an interval.
First of all it DOES work, if you hardcode the values and the function. But I need to read from a file in the format of
5
3.0 2.5 -1.5 0.0 1.7 4.0
6 10
Which means:
It is of degree 5 (no more than 50 ever)
3.0x^5 +2.5x^4 −1.5x^3 +1.7x+4 is the polynomial (we skip ^2 since it's 0)
and the Interval is from 6 to 10
My main concern is the f(x) function which I have hardcoded. I have NO IDEA how to make it take up to 50 besides literally typing out 50 POWS and reading in the values to see what they could be.......Anyone else have any ideas perhaps?
Also what would be the best way to read in the file? fgetc? Im not really sure when it comes to reading in C input (especially since everything i read in is an INT, is there some way to convert them?)
For a large degree polynomial, would something like this work?
double f(double x, double coeff[], int nCoeff)
{
double return_val = 0.0;
int exponent = nCoeff-1;
int i;
for(i=0; i<nCoeff-1; ++i, --exponent)
{
return_val = pow(coeff[i]*x, exponent) + return_val;
}
/* add on the final constant, 4, in our example */
return return_val + coeff[nCoeff-1];
}
In your example, you would call it like:
sampleCall()
{
double coefficients[] = {3.0, 2.5, -1.5, 0, 1.7, 4};
/* This expresses 3x^5 + 2.5x^4 + (-1.5x)^3 + 0x^2 + 1.7x + 4 */
my_integral = f(x, coefficients, 6);
}
By passing an array of coefficients (the exponents are assumed), you don't have to deal with variadic arguments. The hardest part is constructing the array, and that is pretty simple.
It should go without saying, if you put the coefficients array and number-of-coefficients into global variables, then the signature of f(x) doesn't need to change:
double f(double x)
{
// access glbl_coeff and glbl_NumOfCoeffs, instead of parameters
}
For you f() function consider making it variadic (varargs is another name)
http://www.gnu.org/s/libc/manual/html_node/Variadic-Functions.html
This way you could pass the function 1 arg telling it how many "pows" you want, with each susequent argument being a double value. Is this what you are asking for with the f() function part of your question?