Find size of array without using sizeof
&arr
gives you a pointer to the array. (&arr)[1]
is equivalent to *(&arr + 1)
. &arr + 1
gives you a pointer to the array of 100 ints that follows arr
. Dereferencing it with *
gives you that array that follows. Since this array is used in an additive expression (-
), it decays to the pointer to its first element. The same happens to arr
in the expression. So you subtract to pointers, one pointing to the non-existent element right after arr
and the other pointing to the first element of arr
. This gives you 100.
But it's not working. %d
is used for int
. Pointer difference returns you ptrdiff_t
and not int
. You need to use %td
for ptrdiff_t
. If you lie to printf()
about the types of the parameters you're passing to it, you get well-deserved undefined behavior.
EDIT: (&arr)[1]
may cause undefined behavior. It's not entirely clear. See the comments below, if interested.
Generally (as per visual studio),
for an array &arr
is same as arr
,which return the starting base address of our function.
(&arr)[0]
is nothing but &arr
or arr
ex: it will return some address : 1638116
Now, (&arr)[1]
means we are started accessing the array out of bounce means next array or next segment of the size of present array(100 ahead).
ex: it will return some address : 1638216
Now, subtracting (&arr)[1] - (&arr)[0]=100
&arr
is a pointer to an array of 100 int
s.
The [1]
means "add the size of the thing that is pointed to", which is an array of 100 int
s.
So the difference between (&arr)[1]
and arr
is 100 int
s.
(Note that this trick will only work in places where sizeof
would have worked anyway.)