Pointers and Arrays (was: C machine)

Dave Burton daveb at laidbak.UUCP
Sun Jan 31 06:19:51 AEST 1988


In article <3546 at ihlpf.ATT.COM> nevin1 at ihlpf.UUCP (00704a-Liber,N.J.) writes:
>In article <8728 at ism780c.UUCP> marv at ism780.UUCP (Marvin Rubenstein) writes:
>>BTW, the definition of pointer difference in K&R is "if p and q point to
>>members of the same array , p-q is the number of elements between p and q."
>
>I opened up my K&R, skimmed all of chapter 5 (Pointers and Arrays), and could
>not find this anywhere!  (Maybe I didn't look hard enough :-))  I don't think
>this is how K&R defined it (see more comments below).

K&R, Chapter 5, page 98, Paragraph just above last example:
"Pointer subtraction is also valid: if p and q point to members of the
 same array, p-q is the number of elements between p and q."

(Gee, doesn't this look familiar? :-)

>>One way to interpret this is the following:
>>
>>     el1  el2  el3
>>      ^         ^
>>      |         |
>>      p         q
>>
>>As can be seen from the diagram the number of elements "between" p and q is
>>1 (not 2).  Furthermore, the number of elements between p and q is clearly
>>the same as the number of elements between q and p.  i.e, p-q == q-p and no
>>overflow is possible.

At least the way you describe it.
But K&R obviously meant otherwise. Read the example again.

If you really *must* cling to your rendering of "between", just
think of p and q pointing to the _middle_ of their objects, so
the distance between them is 1/2 + 1 + 1/2 = 2.
:-) :-) :-)

I'll agree the wording in K&R was/is poor.
I like H&S's description better: (page 166, first paragraph)
"Given two pointers p and q of the same type, the difference p-q is an integer
 k such that adding k to q yields p. ...
 The subtraction operator may produce unpredictable effects if overflow occurs
 ... or if either operand is a pointer."

>Also, p-q is not equal to q-p (except in the trivial case where q === p).

Such a cute little operator, "===" :-)
-- 
--------------------"Well, it looked good when I wrote it"---------------------
 Verbal: Dave Burton                        Net: ...!ihnp4!laidbak!daveb
 V-MAIL: (312) 505-9100 x325            USSnail: 1901 N. Naper Blvd.
#include <disclaimer.h>                          Naperville, IL  60540



More information about the Comp.lang.c mailing list