Two things to remember about arrays in C:
Except when it is the operand of a sizeof
or unary &
operator, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T
" will be replaced with ("decay to") an expression of type "pointer to T
" whose value is the address of the first element of the array.
In the context of a function parameter declaration, T a[]
and T a[N]
are identical to T *a
; IOW, a
is declared as a pointer to T
, not as an array. Note that this is only true for function parameter declarations.
When you call average(scores)
from your main function, the expression scores
will be replaced with another expression of type double *
, so what average
receives is a pointer value, not an array. Thus, the sizeof
trick to get the number of elements won't work within the average
function. You will have to pass the number of elements in scores
as a separate parameter, like so:
double average(double *scores, size_t count)
{
...
}
and call it as
average(scores, sizeof scores / sizeof *scores); // or pass a constant 3, or
// something similar.