Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!uunet!husc6!cmcl2!brl-adm!brl-smoke!gwyn From: gwyn@brl-smoke.ARPA (Doug Gwyn ) Newsgroups: comp.lang.c Subject: Re: pointer alignment when int != char * Message-ID: <6359@brl-smoke.ARPA> Date: Sat, 29-Aug-87 04:24:37 EDT Article-I.D.: brl-smok.6359 Posted: Sat Aug 29 04:24:37 1987 Date-Received: Sun, 30-Aug-87 07:41:37 EDT References: <493@its63b.ed.ac.uk> <6061@brl-smoke.ARPA> <3812@spool.WISC.EDU> <483@mtxinu.UUCP> <129@minya.UUCP> Reply-To: gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) Organization: Ballistic Research Lab (BRL), APG, MD. Lines: 32 In article <129@minya.UUCP> jc@minya.UUCP (John Chambers) writes: >Huh? This example isn't subtracting pointers to anything. All right, let's try to straighten this out. Ed Gould is correct in noting that the proposed ANSI C standard does not (portably) permit subtraction of pointers to objects not members of the same aggregate. The reason for this is that the process address space may not be flat and linear; in particular, on a segmented architecture, the concept of distance between objects in separate segments may be meaningless. By extension, even though one MAY indeed be able to cast pointers to longs (NOT guaranteed by ANSI C), their difference may not represent anything intelligible, so code that does that has a logic error -- even though it may conform to ANSI C specs. Here is how to find the difference (in number of bytes) of two pointers in various circumstances: If p1 and p2 point to objects of the SAME type (which must be members of the same aggregate): (p2 - p1) / (int)sizeof(type) If p1 and p2 point to objects of DIFFERENT types (which must be members of the same aggregate): ((char *)p2 - (char *)p1) / (int)sizeof(char) The (int) cast can be omitted if you know that p1 is not higher than p2. Division by sizeof(char) can be omitted if you're sure that it is exactly 1 (which seems likely for the final ANSI C standard). The latter formula can be used in all cases, but when it applies, the first is often more convenient. In fact, one usually needs the number of OBJECTS, not the number of BYTES, between two pointers, which is simply p2 - p1