[comp.lang.c] Pointer arithmetic and comparison

bengsig@oracle.nl (Bjorn Engsig) (05/09/89)

In article <13004@haddock.ima.isc.com> karl@haddock.ima.isc.com (Karl Heuer)
writes: [as a reply to article <4646@freja.diku.dk> by njk@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@oracle.nl           / \     take into account Hofstadter's Law"

gwyn@smoke.BRL.MIL (Doug Gwyn) (05/10/89)

In article <320.nlhp3@oracle.nl> bengsig@oracle.nl (Bjorn Engsig) writes:
>The call to malloc gives me 1000 * sizeof int bytes, but is this an array?

From the pANS:

	The pointer returned if the allocation succeeds is suitably
	aligned so that it may be assigned to a pointer to any type
	of object and then used to access such an object or an array
	of such objects in the space allocated (until the space is
	explicitly freed or reallocated).