Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.3 4.3bsd-beta 6/6/85; site columbia.UUCP Path: utzoo!watmath!clyde!burl!ulysses!allegra!mit-eddie!genrad!panda!talcott!harvard!seismo!columbia!eppstein From: eppstein@columbia.UUCP (David Eppstein) Newsgroups: net.lang.c Subject: Re: Re: c programming style - READ THIS Message-ID: <1020@columbia.UUCP> Date: Sat, 31-Aug-85 14:38:03 EDT Article-I.D.: columbia.1020 Posted: Sat Aug 31 14:38:03 1985 Date-Received: Mon, 2-Sep-85 04:10:37 EDT References: <90@rtp47.UUCP> <5400011@prism.UUCP> Reply-To: eppstein@columbia.UUCP (David Eppstein) Organization: Columbia University Lines: 25 In article <5400011@prism.UUCP> mer@prism.UUCP writes: > > Since 'p+n', where p is a pointer and n is an integer, is equivalent to > adding n*sizeof(whatever p points to), the safe and portable way of adding > an integer to a pointer treated as an integer is > (char *)p + n > since (I think) character are always a byte wide. If that's not always the > case, I apologize; on the other hand, it's probably safe than converting > a pointer to an int or a long; I had trouble porting something from a VAX > to a Pyramid because of a cast of this sort. Not the case. For instance on the DEC-20, adding integers to (int *) looks like adding integers to integers but adding them to (char *) does something totally different (divides by number of bytes per word, adds word quotient as an integer, adds number of bytes remainder multiplied by byte size shifted over by 30 bits; bytes per word and bits per byte have to be calculated from the pointer itself because we have both 7-bit bytes packed 5 to a word and 9-bit bytes packed 4 to a word (others too but those are the ones used in C); this is not as bad as it sounds because there is a machine instruction to do it all). On all implementations that I know about, coercing the pointer to (long) and adding your integer will work. However this is still somewhat nonportable and you are better off doing whatever you are trying to do some other, clean, portable way not involving adding integers as integers to pointers.