0

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.

  • 1
    This is a trick that I'm not sure is 100% legal, but I've never caught failing. `&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. – user4581301 Sep 29 '21 at 19:36
  • 1
    So now you know where the array ends. Take that address, subtract the beginning of the array and pointer arithmetic says you'll get a count of the number of elements between the two addresses. End - beginning is the size of the array. These days we use [`std::size`](https://en.cppreference.com/w/cpp/iterator/size), something guaranteed to always work. – user4581301 Sep 29 '21 at 19:36
  • 1
    I've added a better description to the list of duplicate answers. – user4581301 Sep 29 '21 at 19:38
  • 1
    Side note: If you don't have access to `std::size`, it's relatively new, [take a look at the third and fourth possible implementations](https://en.cppreference.com/w/cpp/iterator/size#Possible_implementation). It's stupidly easy to roll your own. – user4581301 Sep 29 '21 at 19:41
  • @user4581301 Thank you for your answer. I guessed that might be the case(adds 1 to &arr move over the entire array) but I was not sure. And yeah it doesn't look like a proper way to get the length. But nice to know the trick all the same. – user3554898 Sep 29 '21 at 20:42

0 Answers0