Pointer-to-array overlapping end of array Pointer-to-array overlapping end of array arrays arrays

Pointer-to-array overlapping end of array


Not an answer but a comment that I can't seem to word well without being a wall of text:

Given arrays are guaranteed to store their contents contiguously so that they can be 'iterated over' using a pointer. If I can take a pointer to the begin of an array and successively increment that pointer until I have accessed every element of the array then surely that makes a statement that the array can be accessed as a series of whatever type it is composed of.

Surely the combination of:1) Array[x] stores its first element at address 'array'2) Successive increments of the a pointer to it are sufficient to access the next item3) Array[x-1] obeys the same rules

Then it should be legal to at least look at the address 'array' as if it were type array[x-1] instead of type array[x].

Furthermore given the points about being contiguous and how pointers to elements in the array have to behave, surely it must be legal to then group any contiguous subset of array[x] as array[y] where y < x and it's upper bound does not exceed the extent of array[x].

Not being a language-lawyer this is just me spouting some rubbish. I am very interested in the outcome of this discussion though.

EDIT:

On further consideration of the original code, it seems to me that arrays are themselves very much a special case in many regards. They decay to a pointer, and I believe can be aliased as per what I just said earlier in this post.

So without any standardese to back up my humble opinion, an array can't really be invalid or 'undefined' as a whole if it doesn't really get treated as a whole uniformly.

What does get treated uniformly are the individual elements. So I think it only makes sense to talk about whether accessing a specific element is valid or defined.


For C++ (I'm using draft N4296) [dcl.array]/7 says in particular that if the result of subscripting is an array, it's immediately converted to pointer. That is, in ptr[0][0] ptr[0] is first converted to int* and only then second [0] is applied to it. So it's perfectly valid code.

For C (C11 draft N1570) 6.5.2.1/3 states the same.


Yes, this is correct code. Quoting N4140 for C++14:

[expr.sub]/1 ... The expression E1[E2] is identical (by definition) to *((E1)+(E2))

[expr.add]/5 ... If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

There is no overflow here. &*(*(ptr)) == &ptr[0][0] == &arr[1].

For C11 (N1570) the rules are the same. §6.5.2.1 and §6.5.6