Itzik984
Itzik984

Reputation: 16824

Arrays and functions in c language

There i something i dont get, if have the following:

double average (double scores[]){

 double sum = 0;
 int n;
 int nscores = sizeof(scores)/sizeof(double);
 for (n=0 ;n<nscores ;++n){
 sum+=scores [n];
 return sum/nscores;
}

and i send this function an array like this:

  double scores[3]={1,2,3};

why will sizeof(scores) will be 0?

Upvotes: 1

Views: 379

Answers (4)

John Bode
John Bode

Reputation: 123596

Two things to remember about arrays in C:

  1. 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.

  2. 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.

Upvotes: 1

Aditya Naidu
Aditya Naidu

Reputation: 1380

scores is a double *const, hence sizeof(scores) will be size required to store a pointer

Upvotes: 0

user405725
user405725

Reputation:

This is because array as a parameter of the function is treated as pointer. For example,

double average (double scores[]);

... is an equivalent to:

double average (double *scores);

and so sizeof(scores)/sizeof(double) is equal to sizeof(double *)/sizeof(double), and if you happen to have those types to be of the same size, the result is 1, but if size of double is 8 and pointer is just 4, then result is 0.

Upvotes: 3

ruakh
ruakh

Reputation: 183602

sizeof(scores), inside the function, is equivalent to sizeof(double *): the compiler has no way to tell, at that point, how big the array was.

It won't be zero, but because sizeof(scores) and sizeof(double) are both integer-type expressions, sizeof(scores)/sizeof(double) is integer division, so if sizeof(scores) < sizeof(double), then sizeof(scores)/sizeof(double) == 0.

Upvotes: 6

Related Questions