Xref: utzoo comp.sys.ibm.pc:22719 comp.sys.intel:635 Path: utzoo!attcan!uunet!husc6!bloom-beacon!mit-eddie!uw-beaver!cornell!batcomputer!sun.soe.clarkson.edu!rpi!rpics!kyriazis From: kyriazis@rpics (George Kyriazis) Newsgroups: comp.sys.ibm.pc,comp.sys.intel Subject: Re: correct code for pointer subtraction Keywords: C pointer math DAMN WELL IS A BUG!!!! Message-ID: <51@rpi.edu> Date: 3 Jan 89 19:01:29 GMT References: <597@mks.UUCP> <3845@pt.cs.cmu.edu> <18123@santra.UUCP> <142@bms-at.UUCP> <6604@killer.DALLAS.TX.US> Sender: usenet@rpi.edu Reply-To: kyriazis@turing.cs.rpi.edu (George Kyriazis) Organization: RPI CS Dept. Lines: 32 In article ron@ron.rutgers.edu (Ron Natalie) writes: >> sizeof(int) == 2 >> so 30000 * 2 =60000 which is to large for a signed int > >Sizeof is irrelevent for pointer math. For subtraction, The result is the >number of "elements" which would be 30000, not 30000 times sizeof >int. For addition, the result is a new pointer, incremented by the >number of elements of the integer added to the pointer. Sizeof is irrelevant? What about the following piece of code: int *a,b[30000]; a = &b[20000]; printf("%d\n", a-b); Obviously when you do the subtraction ( a-b ), the compiler only knows their adrresses, not the number of elements they differ. So it HAS to calculate the diference in BYTES and then divide by sizeof( int ). In example in question ( &a[30000] - a ), the difference in 60000 bytes, which is -5536. Divide it by sizeof(int)==2 and you get the wonderful result: -2736. I am not saying it is correct. Obviously the compiler is doing a signed division to get the result instead of the unsigned that it should do. THAT is the bug. George Kyriazis kyriazis@turing.cs.rpi.edu kyriazis@ss0.cicg.rpi.edu ------------------------------