c programming style - READ THIS

Michael Meissner meissner at rtp47.UUCP
Mon Sep 2 01:15:34 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.
>

This will break down on machines which are bit or word oriented, rather than
byte oriented.  The real question is why do you need to do this in the first
place?

(for word oriented machines, char pointers are typically bigger than word
pointers, and truncatation occurs when converting from un-aligned character
pointers back to word pointers;  the addition typically would create an
un-aligned character pointer)

(for bit oriented machines, adding n to a pointer would actually add 8*n)

	Michael Meissner
	Data General



More information about the Comp.lang.c mailing list