Xref: utzoo comp.sys.ibm.pc:22652 comp.sys.intel:628 Path: utzoo!utgpu!watmath!clyde!att!osu-cis!tut.cis.ohio-state.edu!mailrus!purdue!haven!vrdxhq!bms-at!stuart From: stuart@bms-at.UUCP (Stuart Gathman) Newsgroups: comp.sys.ibm.pc,comp.sys.intel Subject: Re: correct code for pointer subtraction Summary: Do people read their manual's, much less K&R? Keywords: C pointer math *not* a bug. Message-ID: <142@bms-at.UUCP> Date: 29 Dec 88 22:24:51 GMT References: <597@mks.UUCP> <3845@pt.cs.cmu.edu> <18123@santra.UUCP> Organization: Business Management Systems, Inc., Fairfax, VA Lines: 30 In article <18123@santra.UUCP>, tarvaine@tukki.jyu.fi (Tapani Tarvainen) writes: > The same error occurs in the following program > (with Turbo C 2.0 as well as MSC 5.0): > main() > { > static int a[30000]; > printf("%d\n",&a[30000]-a); > } > output: -2768 This is entirely correct. The difference of two pointers is an *int*. If you want an unsigned difference, you need to cast to unsigned (and/or use %u in the printf). If the difference were defined as unsigned, how would you indicate negative differences? If you make the difference long, all the related arithmetic gets promoted also for a big performance hit. The solution is simple, if you want an unsigned ptrdiff, cast or assign to unsigned. This is described in the Turbo C manual. Don't flame the 8086 either. The same thing happens in 32-bit machines (just much less often). 16 bits is 16 bits, and segments are not the problem. The VAX restricts user programs to 31-bit address space to avoid this. -- Stuart D. Gathman <..!{vrdxhq|daitc}!bms-at!stuart>