Hacker News new | ask | show | jobs
by clarry 3461 days ago
No, he isn't correct.

> They also have a provision where a pointer to a nonarray value is treated as if it were a 1-element array

That is not what it says. Let me quote the exact words (emphasis mine):

For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.

You're right that what we have is obviously (a pointer to) an array object, not an element of another array. This is precisely the case where this special provision kicks in, and thus it is legal to do &arr + 1.

1 comments

It looks like we're quoting different standards (or different versions of them). I was referring to ISO C90, which specifically says "nonarray object". I guess yours is C99 or C11?
I quoted from C99 but C11 has the same wording.

I used to prefer C89 but learned the hard way that there are quite a few "bugs" in the standard, where it is ambiguous or otherwise fails to give a clear answer. So C99 is my go-to standard these days, even though I only care for a subset of its features.

"nonarray object" definitely sounds like such a bug. I think the intent of this clause is clear: it is meant to make sure you can always pass a pointer to a single object that treats its argument as a pointer to an array element, and does pointer arithmetic on it. One of the most common construct is simply looping over an array by incrementing the pointer, and this must work without producing an overflow when the pointer points past the array, the way it's conventionally written. If it weren't for this clause, passing a pointer to a single object to be treated as an array of size 1 would break a lot of code. Going further, is the object allocated by malloc an array or a nonarray? That would then be a critical question to ascertaining the correctness of most code out there.

And I cannot think of any reason why only pointers to nonarray objects should be usable in this manner.