Consider an array defined as :
int arr[] = {1, 2, 5, 8, 3, 1, 4};
size_t arr_size = sizeof(arr) / sizeof(arr[0]);
That
sizeof
nonsense is ugly, and it’s often hidden behind a macro. But we can simplify it using pointer arithmetic.
size_t arr_size = *(&arr + 1) - arr;
If you're wondering how does it work, go on :
&arr
is a pointer to the array. It points at the same memory address as arr
. But arr
decays to a pointer to first element.
That means &arr + 1
points at the address after the end of the array.
Dereferencing to *(&arr + 1)
gives the address after the end of the last element (which is again the same address as &arr + 1
with a different type; Similar to arr
and &arr
as *&arr
is equivalent to arr
).
Finally, we can subtract the pointer to the first element to get the length of the array :
*(&arr + 1) - arr
. (Remember this is pointer arithmetic; Subtraction gives the total number of objects between them).