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