I was searching for a way to find the size of an array in C without using sizeof
and I found the following code:
int main ()
{
int arr[100];
printf ("%d\n", (&arr)[1] - arr);
return 0;
}
Can anyone please explain to me how is it working?
Best Answer
&arr
is a pointer to an array of 100int
s.The
[1]
means "add the size of the thing that is pointed to", which is an array of 100int
s.So the difference between
(&arr)[1]
andarr
is 100int
s.(Note that this trick will only work in places where
sizeof
would have worked anyway.)