(really Subtracting them) Re^2: Adding two pointers

Niels J|rgen Kruse njk at freja.diku.dk
Thu May 11 08:15:46 AEST 1989


I still can't get the last pieces of the puzzle to fit, so here
goes again (for the last time i hope, so bear with me).

karl at haddock.ima.isc.com (Karl Heuer) writes:

>In article <4646 at freja.diku.dk> njk at freja.diku.dk (Niels J|rgen Kruse) writes:
>>The word "array" as used when saying that two pointers must point into the
>>same array in order to subtract them is a bit foggy to me.  What about
>>      struct { char c; double d; } x[10];
>>Are (& x[3].d) and (& x[7].d) not pointing into x?

>Not in this sense.  They point into (different) arrays of type `double [1]'.
[1]

>>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.
[2]

>>What array is (char *)x pointing into?

>An array of type `char [sizeof(x)]' (or equivalently, `char [10*sizeof(S)]'
>where S is the struct type) whose existence is supposedly implied by the pANS
>statement that `objects are composed of bytes'.
[3]

Let's change the dimension of x to (sizeof (double) + 1) for
the rest of the discussion.

[1] implies that (& x[0].d + sizeof (*x)) is undefined, since
sizeof (*x) is beyond the bound of the array that (& x[0].d) is
pointing into. But [3] seem to imply that ((char *)& x[0].d) is
pointing into an array of type 'char [sizeof (x)]', starting at
(char *)&x. Thus
(double *)((char *)& x[0].d + sizeof (*x) * sizeof (double))
is defined (and equal to & x[sizeof (double)].d).

To sum it up, we have a pointer to double (ptr) and an index (inx),
such that (ptr + inx) is undefined, yet
(double *)((char *)ptr + inx * sizeof (double))
_is_ defined.

Not nice.

On the other hand, if (& x[0].d + sizeof (*x)) _is_ defined, we
have (& x[0].d + sizeof (*x) == & x[sizeof (double)].d), yet
(& x[sizeof (double)].d - & x[0].d) is undefined by [1] because
they point into different arrays.

Not nice either.

The argument in [2] doesn't apply to
(& x[sizeof (*x)].d - & x[0].d), i think.
-- 
         Niels J|rgen Kruse
Email    njk at diku.dk
Mail     Tustrupvej 7, 2 tv, 2720 Vanlose, Denmark



More information about the Comp.lang.c mailing list