1

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?

Itzik984
  • 15,968
  • 28
  • 69
  • 107

4 Answers4

6

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.

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • so why do i get a 0? sizeof(scores)=sizeof(void*)=4? and the division is 0? – Itzik984 Feb 07 '12 at 22:14
  • 2
    @Itzik984: Yes, exactly. On your platform, `sizeof(double *)` is `4` and `sizeof(double)` is `8`, so `sizeof(scores)/sizeof(double)` is `4/8`, which is `0`. – ruakh Feb 07 '12 at 22:15
3

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.

1

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.
John Bode
  • 119,563
  • 19
  • 122
  • 198
0

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

Aditya Naidu
  • 1,362
  • 9
  • 12