c programming style - READ THIS

David Eppstein eppstein at columbia.UUCP
Sun Sep 1 04:38:03 AEST 1985


In article <5400011 at prism.UUCP> mer at 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.



More information about the Comp.lang.c mailing list