MOHAMED
MOHAMED

Reputation: 43558

pointer comparisons "<" with one past the last element of an array object

I know the pointer comparisons with < is allowed in C standard only when the pointers point at the same memory space (like array).

if we take an array:

int array[10];
int *ptr = &array[0];

is comparing ptr to array+10 allowed? Is the array+10 pointer considered outside the array memory and so the comparison is not allowed?

example

for(ptr=&array[0]; ptr<(array+10); ptr++) {...}

Upvotes: 9

Views: 1797

Answers (2)

Michael Burr
Michael Burr

Reputation: 340396

Yes, a pointer is permitted to point to the location just past the end of the array. However you aren't permitted to deference such a pointer.

C99 6.5.6/8 Additive operators (emphasis added)

if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. 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. If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

And, specifically for comparision operations on pointers:

C99 6.5.8/5 Relational operators

If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P. In all other cases, the behavior is undefined.

Upvotes: 10

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 248199

Yes, that is allowed, and C++ relies heavily on it (C doesn't use it quite as much, but in C++, a very common way to denote ranges is by have a pointer (or more generally, an iterator) pointing to the first element, and another pointing one past the end of the range.

It is legal for such a pointer to exist, and to compare it against the rest of the array.

But it is not legal to ever dereference the pointer.

Upvotes: 5

Related Questions