Home > database >  Why does my C function doesny print anything?
Why does my C function doesny print anything?

Time:12-03

Here is my main function:

void arrCalc(int*, int, int*, int*, int*, double*, int*);
int main()
{
    int a[5] = {1, 2, 3, 4, 5}, n = 5, *max, *min, *sum, *isEven;
    double *avg;
    arrCalc(a, n, max, min, sum, avg, isEven);
    printf("%d %d %d %lf %d", *max, *min, *sum, *avg, *isEven);
    return 0;
}

And here is my fution:

void arrCalc(int *arr, int n, int *max, int *min, int *sum, double *avg, int *isEven)
    int i;
    *min = arr[0];
    *max = arr[0];
    for (i = 0; i < n; i  )
    {
        if (arr[i] < *min)
            *min = arr[i];
        if (arr[i] > *max)
            *max = arr[i];
        if (!(arr[i] % 2))
            *isEven = 1;
        *sum  = arr[i];
    }
    *avg = (double) *sum / n;
}

When i run the program it prints me nothing. I think it's somehow connected to the definition if min and max in arrCalc. Can someone correct my code please?

CodePudding user response:

In main(), you declare min, max, sum, and isEven as int*, but you don't allocate any space for the actual int's that they're supposed to be pointing to. You should just declare these variables as int in main, and then pass pointers to them to your arrCalc function, like this:

int main()
{
    int a[5] = {1, 2, 3, 4, 5}, n = 5, max, min, sum, isEven;
    double avg;
    arrCalc(a, n, &max, &min, &sum, &avg, &isEven);
    printf("%d %d %d %lf %d", max, min, sum, avg, isEven);
    return 0;
}
  • Related