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?

4
  • This may be useful to you. stackoverflow.com/questions/33523585/… Commented Apr 30, 2020 at 2:44
  • This will 100% help: stackoverflow.com/questions/2528318/… Commented Apr 30, 2020 at 3:50
  • there's another question exactly about this but the site doesn't correctly search for &x + 1 etc. ;( Commented Apr 30, 2020 at 3:56
  • see here or here for discussion of whether this is legal or not Commented Apr 30, 2020 at 4:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Initially, I was also thinking that but it should be defined behavior!
"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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.