-3
    void testSizeof(double array[])
    {
        printf ("%i\n", sizeof(array));
    }

When calling this function, the output is not the length of the array.

Why?

Then, what are the facts about the output?

Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72
Simon Li
  • 11
  • 1

1 Answers1

5

It returns the size of the double pointer, i.e. sizeof(double*).

When a function takes an argument of type double[], this is exactly the same as taking an argument of type double*. The array is said to decay into a pointer.

For further explanation, see What is array decaying? and the C FAQ.

If the function needs to know the size of the array, you have to pass it explicitly. For example:

void testSizeof(double array[10]) {...}

or

void testSizeof(double array[], size_t array_size) {...}

In the first example, the array is also subject to pointer decay. However, since you already know the size of the array, you wouldn't need to use sizeof() to figure it out.

It goes without saying that the second approach is much more flexible than the first.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • The second will be ok, but the first one...(http://codepad.org/5kqzjvib). Thanks, in fact I wonder what did sizeof operator do when in the fuction define in my qusetion. – Simon Li Mar 04 '13 at 08:19
  • @SimonLi: That's not what I meant. If the function takes `double[20]`, it already knows the array has `20` elements. It doesn't need `sizeof()`. In any case, I've updated the answer. – NPE Mar 04 '13 at 08:21
  • Oh, I see! So, in fact the output is sizeof(double *)? – Simon Li Mar 04 '13 at 08:30