Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++) {...}
like image 978
MOHAMED Avatar asked Apr 26 '13 10:04

MOHAMED


1 Answers

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.

like image 153
Michael Burr Avatar answered Nov 06 '22 21:11

Michael Burr