Search code examples
cpointersaverageprogram-entry-point

C, how to call a function


#include <stdio.h>

void average(float age[]);

int main(void)
{
    float *p;
    float avg = 0.0;
    float age[] = { 23.4, 55, 22.6, 3, 40.5, 18 };
    p = &age[0];
    avg = average(age);
    printf("\n\nAverage age = %.2f\n\n\n", avg);
    return 0; // this should return the average age from the void average() function
}

void average(float age[])
{
    float *p;
    p = &age[0];
    int i = 0;
    float avg = 0.0 , sum = 0.0;
    for (i = 0; i < 6; ++i) 
    {
        sum += *(p+i);
    }
    avg = (sum / 6);
    //return avg; // this should be a return 0 (to go with the void)
}

Hi I am very very new to C, I am supposed to make the function "average" a void which i have done and then output everything in the main. Im not sure how to go about this, everything I try i get errors. I'd like to do it without creating another function if possible.


Solution

  • I'm assuming this is part of an assignment, and the lesson they're trying to teach you is probably how to use pointers to manipulate values. A void function doesn't return anything at all, so your current code doesn't give you an average. Here's the change you should make:

    void average(float age[], float *avg);
    
    int main(void)
    {
        float *p;
        float avg = 0.0;
        float age[] = { 23.4, 55, 22.6, 3, 40.5, 18 };
        p = &age[0];
        average(age, &avg);
        printf("\n\nAverage age = %.2f\n\n\n", avg);
        return 0; // this should return the average age from the void average() function
    }
    
    void average(float age[], float *avg)
    {
        float *p;
        p = &age[0];
        int i = 0;
        *avg = 0.0;
        float sum = 0.0;
        for (i = 0; i < 6; ++i) 
        {
            sum += *(p+i);
        }
        *avg = (sum / 6);
        //return avg; // this should be a return 0 (to go with the void)
    }
    

    You're passing in a pointer to the average function, and it acts on the value of that memory address.

    Here's some more information about pointers in C. https://study.cs50.net/pointers