1
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
    int  arr[] = {1, 2, 3, 4, 5, 6}; 
    int size = *(&arr + 1) - arr; 

    return 0; 
} 

How does int size = *(&arr + 1) - arr; find the size of the array exactly? I've read the explanation from geeksforgeeks and still a bit confused. I thought if you dereferenced (&arr + 1) then it would give you a nonexistent value since you're skipping ahead 6 integers, which can be anything random in that memory address? And also, if you're able to dereference (&arr + 1) to an int type, then how are you able to subtract that value from arr?

pancakes324
  • 11
  • 1
  • 3
  • This may be useful to you. https://stackoverflow.com/questions/33523585/how-do-sizeofarr-sizeofarr0-work – baseballr Apr 30 '20 at 02:44
  • This will 100% help: https://stackoverflow.com/questions/2528318/how-come-an-arrays-address-is-equal-to-its-value-in-c – abhiarora Apr 30 '20 at 03:50
  • there's another question exactly about this but the site doesn't correctly search for &x + 1 etc. ;( – M.M Apr 30 '20 at 03:56
  • [see here](https://stackoverflow.com/questions/988158/) or [here](https://stackoverflow.com/questions/52727045/) for discussion of whether this is legal or not – M.M Apr 30 '20 at 04:02

1 Answers1

1

*(&arr + 1) - arr is a pretty complicated way to write 6.

&arr is a pointer to an int[6]

(&arr + 1) is a pointer to an int[6] that starts after the one at arr, i.e., it's 6 ints higher in memory.

*(&arr + 1) is that imaginary array after arr. There is no array there, but we're not going to use it, so it doesn't matter.

In *(&arr + 1) - arr, the two integer arrays are converted to int * pointers to their first elements before the difference operation is applied. Since these arrays are 6 ints apart in memory, there are 6 ints between those two pointers, and the result is 6.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87
  • Initially, I was also thinking that but it should be defined behavior! – abhiarora Apr 30 '20 at 03:59
  • "There is no array there, but we're not going to use it, so it doesn't matter." - the code is still technically undefined behaviour since the semantics of the `*` operator are only defined for the case where the pointer points to a valid object, making the behaviour undefined by omission. There is an open CWG issue about the subject – M.M Apr 30 '20 at 04:05