Error in C program in Dynamic memory allocation

I am using gcc compiler in ubuntu18.10 os. And I don't know why this program is giving Error and Can't even understand the error. The Program is as follows and I presented ERRORS also.

#include<stdio.h>
#include<stdlib.h>

float Average(int*, int);

int main()
{
 int *arr;
 int n;
 scanf("%d",&n);
 float sum;
 arr = (int *)malloc(n * sizeof(int));
 for(int i=0;i<n;i++)
    scanf("%d",&arr[i]);

 sum = Average(int *arr, int n);
 printf("%f\n",sum);
 return 0;
}
float Average(int *arr, int size)
{
  int sum;
  int n = size;
  printf("arr: %p\n",&arr);
  printf("size: %p\n",&size);
  printf("sum: %p\n",&sum);

  for(int i=0;i<n;i++)
  {
    sum += arr[i];
  }
  return (sum * 1.0f) / size;
}

Errors are:

Test.c: In function ‘main’:
Test.c:16:16: error: expected expression before ‘int’
  sum = Average(int *arr, int n);
                ^~~
Test.c:16:8: error: too few arguments to function ‘Average’
  sum = Average(int *arr, int n);
        ^~~~~~~
Test.c:4:7: note: declared here
 float Average(int*, int);
       ^~~~~~~

Please Help me to find out why and any reference materials to understand the concept clearly. Thank you

Upvotes: 0

Views: 74

Answers (2)

paxdiablo
paxdiablo

Reputation: 881113

sum = Average(int *arr, int n);

Type specifiers are something you give in the declaration and definition of the function, not in calls to it. You want:

sum = Average(arr, n);

Some other things you may want to check.

First, the int sum; in Average() does not initialise the value to zero, it sets it to some arbitrary value. That's not going to end well when you just add the integers to it. It should instead be:

  int sum = 0;

Second, unless you're using massive arrays of floating point numbers, it's almost always better to use double for its greater range and precision.


Taking those into account, I probably would have written the function:

double Average(int *arr, int size) {
    double sum = 0;
    for (int i = 0; i < size; ++i)
        sum += arr[i];
    return sum / size;
}

Upvotes: 2

dbush
dbush

Reputation: 223689

When you call a function you don't specify the types of the arguments. That's a syntax error. If you look at where you call printf, you'll see that you don't specify the parameter types there. The same goes for your own functions.

So change this:

sum = Average(int *arr, int n);

To this:

sum = Average(arr, n);

Upvotes: 0

Related Questions