Xref: utzoo comp.sys.ibm.pc:22253 comp.sys.intel:602 Path: utzoo!attcan!uunet!lll-winken!lll-tis!ames!mailrus!iuvax!bobmon From: bobmon@iuvax.cs.indiana.edu (RAMontante) Newsgroups: comp.sys.ibm.pc,comp.sys.intel Subject: Re: correct code for pointer subtraction Summary: Leaping into the fray... Message-ID: <15813@iuvax.cs.indiana.edu> Date: 15 Dec 88 02:19:16 GMT Reply-To: bobmon@iuvax.UUCP (RAMontante) Organization: malkaryotic Lines: 44 Referring to Eric Gisin's code (appended): Although "diff()" is being called with two pointers to the same object, it doesn't know that. In general it knows only that it's getting two pointers to a struct "six". Since the pointers are passed by value, they may as well be pointers into distinct objects; and they certainly aren't guaranteed to be represented with identical segments. (Again, in general there's no assurance that they _could_ be.) My TurboC manual indicates that, except in huge model, pointers are tested for inequality by using only the offsets (16 bits). Inequality tests often look like subtraction, so I wouldn't be surprised if pointer subtraction also used only offsets. (Huge-pointer comparisons use the full address, in normalized form.) So I agree with Bill Davidsen that the rigorous way to do this is to cast the pointers to huge, and subtract the casts. Viz., int diff(struct six far *p, struct six far *q) { return (int)( (struct six huge *)p - (struct six huge *)q ); } Beauty, eh? ________________ In article <600@mks.UUCP> egisin@mks.UUCP (Eric Gisin) writes: + +Please read my code. I have two pointers to "s", a single object. +Declaring "s" with 1 or 10000 makes no difference. +And the pointers are seperated by 60000, which is less than 64K. + +struct six { /* HINT: this struct is 6 bytes long */ + 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 */ +}