Xref: utzoo comp.sys.ibm.pc:22065 comp.sys.intel:591 Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!nrl-cmf!ukma!rutgers!rochester!pt.cs.cmu.edu!b.gp.cs.cmu.edu!ralf From: ralf@b.gp.cs.cmu.edu (Ralf Brown) Newsgroups: comp.sys.ibm.pc,comp.sys.intel Subject: Re: correct code for pointer subtraction Message-ID: <3845@pt.cs.cmu.edu> Date: 10 Dec 88 02:20:02 GMT References: <597@mks.UUCP> Organization: Carnegie-Mellon University, CS/RI Lines: 32 In article <597@mks.UUCP> egisin@mks.UUCP (Eric Gisin) writes: -How come I can't find a compiler that generates correct -code for pointer subtraction in C on 8086s? -Neither Turbo, Microsoft, or Watcom do it right. -Here's an example: - -struct six { - int i[3]; -}; -int diff(struct six far* p, struct six far* q) { - return p - q; -} -main(void) { - struct six s[1]; - printf("%d\n", diff(s+10000, s)); /* 10000 */ - printf("%d\n", diff(s, s+100)); /* -100 */ -} - -All of the compilers I tried computed a 16 bit difference, -then sign extended it before dividing. -This does not work if the pointers differ by more than 32K. In addition to HUGE model, which someone already pointed out, I would like to mention that K&R only guarantees valid results for pointer subtractions between pointers to the SAME array. In non-HUGE models, the largest object is 64K, so for multi-byte data types, the result is correct (since they can't differ by more than 32K objects). For char arrays, you would have an ambiguity as to which pointer points lower in the array. -- {harvard,uunet,ucbvax}!b.gp.cs.cmu.edu!ralf -=-=- AT&T: (412)268-3053 (school) ARPA: RALF@B.GP.CS.CMU.EDU |"Tolerance means excusing the mistakes others make. FIDO: Ralf Brown at 129/31 | Tact means not noticing them." --Arthur Schnitzler BITnet: RALF%B.GP.CS.CMU.EDU@CMUCCVMA -=-=- DISCLAIMER? I claimed something? --