Pointer arithmetic and comparison

Bjorn Engsig bengsig at oracle.nl
Tue May 9 22:46:21 AEST 1989


In article <13004 at haddock.ima.isc.com> karl at haddock.ima.isc.com (Karl Heuer)
writes: [as a reply to article <4646 at freja.diku.dk> by njk at freja.diku.dk
(Niels J|rgen Kruse)]
>
>>Is (&x[3].d - &x[7].d) undefined?
>
>Yes (even after I fixed the typo).  On some machines, there does not exist an
>integer k such that (&x[1].d == &x[0].d + k), so it would be meaningless to
>attempt to evaluate (&x[1].d - &x[0].d) to any integer.
This made me read the sections on pointer arithmetic and comparison in
K&R, 2nd. issue, and I made the following rather hypotetical thought:

- Pointer arithmetic (p + i, p - i, p1 - p2) is only guaranteed to work
  if the p's point to members of the same array.

- Pointer comparison (p1 < p2, etc.) is only guaranteed to work if the p's
  point to parts of the same object (array, struct or union).

If I do something like

	int *p, *p1, *p2;
	p = (int *) malloc( 1000 * sizeof int )
	p1 = p+7; p2 = p+17;

how am I then guaranteed that p points to an array of int's, or more
interestingly that it is true that p2-p1==10 and p1<p2 ?  The call to 
malloc gives me 1000 * sizeof int bytes, but is this an array?
-- 
Bjorn Engsig, ORACLE Europe         \ /    "Hofstadter's Law:  It always takes
Path:   mcvax!orcenl!bengsig         X      longer than you expect, even if you
Domain: bengsig at oracle.nl           / \     take into account Hofstadter's Law"



More information about the Comp.lang.c mailing list