I am trying to learn about arrays in c and was writing a function which could take an average of an array and return it:
#include <stdio.h>
float avg(float list[]);
int main() {
/* list of marks, declared as an array */
float marks[]={4.0, 6.0, 7.0, 5.0, 6.0, 8.0,
10.0, 3.0, 9.0, 4.0};
int i, n;
n=10;
printf("Marks: ");
for (i=0;i<n;i++) {
printf("%.1f ",marks[i]);
}
printf("\n");
float max;
int studentno;
max = marks[0];
for(i=0;i<n;i++){
if(marks[i]>max){
max=marks[i];
studentno=i;
}
}
printf("student %d recieved the highest score of %1.1f, while the average mark was %1.1f \n",studentno,max,avg(marks));
return 0;
}
float avg(float list[]){
int n;
int i;
float sum;
sum=0;
n=10;
for(i=0;i<n;i++){
sum+=list[i];
}
return sum/n;
}
The above code works fine, but I wanted to try to make it more general so that I could apply the function avg
to any list, rather than a size 10 list. To do this I changed the line n=10
in my function body, to n=sizeof(list)/sizeof(list[0])
.
When I tried to run the code again, I received the following error which I can not understand.
gcc 3Q2.c -o 3Q2
3Q2.c: In function ‘avg’:
3Q2.c:36:10: warning: ‘sizeof’ on array function parameter ‘list’ will return size of ‘float *’ [-Wsizeof-array-argument]
n=sizeof(list)/sizeof(list[0]);
^
3Q2.c:31:17: note: declared here
float avg(float list[]){
^~~~
Why does this happen?