Alex Rivera | Logout

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

Asked 2013-04-26T10:07:19.417
9

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++) {...}
Edit
Report

1 Answer

5

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.

answered 2013-04-26T10:14:08.740

Your Answer