I saw one approach to calculate the length of an array is like this:
int arr[5] = {5, 8, 1, 3, 6};
int len = *(&arr + 1) - arr;
I understand basic pointer arithmetic. For example arr + 1
move the pointer to the 2nd element in the array and the value of arr + 1
is the address of the 2nd element.
However I'm confused about what &arr + 1
does. I tried printing out the value of &arr
and it's the same as arr
, both are the address of the 1st element in the array. Any help is appreciated.
&arr
is the address of the the array. It has the same address as the first element of the array, but here the compiler knows it refers to the entire array, so adding 1 to it advances the pointer by the whole array, not just one element. You wind up with a pointer to the next address after the end of the array. dereference it and you get a pointer to what would be the first array element after the end of the array.std::size
, something guaranteed to always work.std::size
, it's relatively new, take a look at the third and fourth possible implementations. It's stupidly easy to roll your own.