Array length can be calculated using *(&arr+1)-arr
which then simplifies to (&arr)[1]-arr
which further simplifies to 1[&arr]-arr
.
But when the length is calculated in a function different from where memory allocation has been done, wrong results are computed.
For instance,
#include <iostream>
#define ARRAY_SIZE(arr) (1[&arr]-arr)
using namespace std;
void func(int *arr)
{
cout<<ARRAY_SIZE(arr)<<endl;
}
int main()
{
int arr[]={1,2,3,4,5};
cout<<ARRAY_SIZE(arr)<<endl;
func(arr);
}
This gives the output:
5
8
What accounts for such strange behaviour?