Hacker News new | ask | show | jobs
by Buge 3461 days ago
It's a complicated situation. There's a pointer to an array, and that pointer is dereferenced, resulting in an array (that then decays to a pointer). But that second array/pointer is not dereferenced. I'm not sure if it's legal.
1 comments

Where is it dereferencing the array?

    *(&arr + 1) - arr
That translates to taking the address one point past the array and subtracting the address of the array from it. It doesn't actually dereference the location past the end of the array.

While:

    (&arr)[1] - arr
might appear to be doing something different, it actually isn't.
&arr is a pointer to an array (it points to the existing array).

&arr + 1 is a pointer to an array that begins just after the existing array.

* is the dereference operator, so it seems to me that *(&arr + 1) dereferences the pointer to the array, resulting in an array (or a reference to an array), which then decays to a pointer.

>so it seems to me that (&arr + 1) dereferences the pointer to the array

It doesn't. Because an array is already a pointer, in (&arr + 1) &arr is a pointer to a pointer (ie, a handle) so *(&arr) is dereferencing the handle to the pointer. So it's still one pointer level deep - it doesn't dereference it completely.

It doesn't matter what it is a pointer to, type-wise. It is still a pointer one-past-the-end, and it is being dereferenced.

Also, &arr is not a pointer to a pointer. It's a pointer to an array. Specifically, its type is int(* )[5] in this example, and so when you dereference it, the result is of type int[5]. So if you do e.g. sizeof(* &arr + 1), you'll get 5 * sizeof(int).

Ah, but since it is dereferencing an array... you haven't actually dereferenced to the memory location yet. If you had, you wouldn't be possible to subtract a pointer from it.