incrementing after a cast

Henry Spencer henry at utzoo.UUCP
Fri Dec 5 04:47:03 AEST 1986


>		char *chp;
>		L = *((sometype *) chp)++;
>
>The idea of the cast is to force chp to be incremented by the size of
>sometype.  [But K&R says it's illegal.]

It is illegal.  There are messier ways of getting around that, but you are
making a fundamental mistake regardless.  What you are saying is "treat chp
as a sometype pointer, and increment it".  There is no guarantee that the
"increment a sometype pointer" operation bears any relation to the "add n
to a char pointer" operation.  The two kinds of pointers may not even be
the same size!

If you wish to do this cleanly, the following is not guaranteed but is more
likely to do the right thing on a wide variety of machines:

		char *chp;
		L = *(sometype *)chp; chp += sizeof(sometype);
-- 
				Henry Spencer @ U of Toronto Zoology
				{allegra,ihnp4,decvax,pyramid}!utzoo!henry



More information about the Comp.lang.c mailing list