Path: utzoo!utgpu!watmath!clyde!att!osu-cis!killer!ames!xanth!nic.MR.NET!umn-d-ub!rutgers!ucsd!ucbvax!hplabs!hpfcdc!hpislx!hplvli!boyne From: boyne@hplvli.HP.COM (Art Boyne) Newsgroups: comp.sys.ibm.pc Subject: Re: Re: correct code for pointer subtraction (LONG reply) Message-ID: <360005@hplvli.HP.COM> Date: 4 Jan 89 16:04:42 GMT References: <2245@iscuva.ISCS.COM> Organization: Loveland Inst. Div Lines: 39 chasm@killer.DALLAS.TX.US (Charles Marslett) writes: > In article <142@bms-at.UUCP>, stuart@bms-at.UUCP (Stuart Gathman) writes: > > 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*. > > And unless you have a 15-bit computer, 30000 is a very representable *INT*, > so please pay attention to the discussion before asserting something. The > compiler is generating a VERY WRONG ANSWER. Ok guys, just hold it a minute and think: it only hurts for a little while. Let's look at what the compiler is trying to do: &a[30000]-a where a is an integer array. First, int's are 16-bit, ie., 2 bytes/int. So, a[30000] is located 60000 bytes away from a[0]. Ideally, the calculation should look like take address of a[30000] subtract address of a[0] divide by 2 to convert offset to integer pointer difference But &a[30000]-a = 60000 bytes, too big for a 16-bit signed int. Unsigned 60000 looks like -5536 signed. Divided by 2 is -2768. Voila. You can argue that the compiler should use unsigned arithmetic for the pointer calculation, or do a 32-bit calculation, but given the assumptions the compiler operates under, the answer is reasonable (but not useful). Art Boyne, boyne@hplvdz.HP.COM