0

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?

Vishal Jain
  • 443
  • 4
  • 17
  • See some of the answers in the above question. When an array is passed to a function it decays to a pointer. Which means `sizeof(list)` in your code is actually `sizeof(float *)` and is thus not the size of the array as you intended. – kaylum Feb 25 '20 at 10:10
  • your `list` is a pointer on a float. when you write `sizeof (list)` you will return the size of the pointer and not the size of ALL the memory space allocated for your `list`. For example : `int *p; float *f; int i = sizeof(p); int j = sizeof(f);` Here : **i = j** – Landstalker Feb 25 '20 at 10:13
  • That explains the first error, what about the second? Why does the 'note: declared here' error crop up? – Vishal Jain Feb 25 '20 at 10:21
  • 1
    @V.Jain The compiler tells you where this variable is declared. It's like when you make a double declaration of a function : he tells you: the first declaration is here, the second there ... – Landstalker Feb 25 '20 at 10:24
  • @V.Jain you say : **while it has been declared as a float in my function argument?** No, your argument is not a **float**, your argument is a **float [ ]** – Landstalker Feb 25 '20 at 10:27

0 Answers0