Despite the syntax used for its definition void func(int arr[])
, function func
receives a pointer to the first element of the array. The definition is clearer as void func(int *arr)
.
The expression *(&arr+1)-arr
evaluates at compile time to the number of elements of an array only if arr
is defined as an array. If arr
is a pointer, it dereferences memory after the pointer and subtracts the pointer value, which is meaningless and in most circumstances has undefined behavior.
A more common (and more readable) expression to get the number of element of an array is
n = sizeof(arr) / sizeof(*arr);
If arr
is an array, dividing its size in bytes by the size of an element in bytes produces the number of elements. The expression is evaluated at compile time, no runtime overhead. If arr
is a pointer, dividing its size by the size of the type it points to is defined, but useless, just like your expression.