Search code examples
cpass-by-referencefunction-definitionfunction-call

How can I call the following void function with double parameters?


This is what I have currently, and I have no idea what to do to make it run:

void avg_sum(double a[], int n, double *avg, double *sum) {   
    int i;
    *sum = 0.0;

    for (i = 0; i < n; i++)
        *sum += a[i];

    *avg = *sum / n; 
}

int main () {
    int array[5] = {1, 2, 3, 4, 5};
    int avg = 3;
    int sum = 2;

    avg_sum(array, 5, avg, sum);
}

I tried manipulating the arguments for running the function, but I can't figure out how to make it work. It can be simple, I just have to write a program to test the avg_sum function. That portion must remain the same.


Solution

  • You want this:

    int main () {
        double array[5] = {1, 2, 3, 4, 5};  // use double
        double avg = 3;
        double sum = 2;
    
        avg_sum(array, 5, &avg, &sum);      // call with &
    }
    
    • avg_sum operates on doubles, therefore you need to provide doubles.
    • parametrers 3 and 4 must be pointers to double, therefore you need to use the address operator &.

    All this is covered in the first chapters of your beginner's C txt book.