Find size of array without using sizeof

arrayscsizeof

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 100 ints.

The [1] means "add the size of the thing that is pointed to", which is an array of 100 ints.

So the difference between (&arr)[1] and arr is 100 ints.

(Note that this trick will only work in places where sizeof would have worked anyway.)