Why sizeof(param_array) is the size of pointer?

c

Solution

A special C rule says that for function parameters, array types are adjusted to pointer types. That means:

`int length(int array[]);`

is equivalent to

`int length(int *array);`

So when you compute the `sizeof` the array you are actually computing the size of the pointer.

(C99, 6.7.5.3p7) "A declaration of a parameter as "array of type" shall be adjusted to "qualified pointer to type", where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation."

Problem

I want to get the length of an array, say `int array[] = {1, 2, 3, 4}`. I used `sizeof` to do that. ``` int length(int array[]) { return sizeof(array) / sizeof(int); } int main() { int array[] = {1, 2, 3, 4}; printf("%d\n", length(array)); // print 1 printf("%d\n", sizeof(array) / sizeof(int)); // print 4 } ``` So, why the `sizeof(array)` in function `length` returns the pointer size of `array`? But in function `main`, it works. And, how should I modify the `length` function to get an array's length?

Original source

Related problems