This is the code below to illustrate the issue:
#include <stdio.h>
void func(int arr[]);
int main() {
int arr[10];
int n = *(&arr + 1) - arr;
printf("%d\n", n);
func(arr);
return 0;
}
void func(int arr[]) {
int n = *(&arr + 1) - arr;
printf("%d\n", n);
}
Output of the above code is:
10
268435906
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With