c - Does it make sense to compare which one of two points to two entries of an array is bigger? -
in c, have array int a[20]
. have 2 pointers int *pi
, int *pj
pointing 2 entries a[i]
, a[j]
respectively. don't know i
, j
. know if i > j
or j<i
or i==j
.
my thought comparing pi
, pj
based on pi = + i
, pj=a+j
. wonder if correct i > j
if , if pi>pj
, , i == j
if , if pi==pj
? thanks!
yes, <
, >
operators on pointers defined work in way.
and pointers don't point same object or past end of it, behavior of <
, >
undefined. ==
, !=
defined, though.
reference: n1570 6.5.8, paragraph 5:
when 2 pointers compared, result depends on relative locations in address space of objects pointed to. if 2 pointers object types both point same object, or both point 1 past last element of same array object, compare equal. if objects pointed members of same aggregate object, pointers structure members declared later compare greater pointers members declared earlier in structure, , pointers array elements larger subscript values compare greater pointers elements of same array lower subscript values. pointers members of same union object compare equal. if expression
p
points element of array object , expressionq
points last element of same array object, pointer expressionq+1
compares greaterp
. in other cases, behavior undefined.
Comments
Post a Comment