Determing alignment of (char *) pointer

Ron Natalie <ron> ron at brl-sem.ARPA
Tue Dec 9 15:15:38 AEST 1986


In article <3798 at watmath.UUCP>, rbutterworth at watmath.UUCP (Ray Butterworth) writes:
> In article <1510 at mit-trillian.MIT.EDU>, newman at mit-trillian.MIT.EDU (Ron Newman) writes:
> > 
> >    char *p;
> >    /* method 1 */
> >    if ((long)p & 3) ...
> >    /* method 2 */
> >    if ((long)(p - (char *) 0) & 3) ...
> 
> As far as I know, all C compilers will return the integral number
> of bytes between the two pointers in method 2.  It should always
> work (and there is no need for the (long) cast.  (There might be
> compilers out there in which (sizeof(char))!=1, I don't know.)

First, sizeof (char) has to be 1.  Second, method 2 assumes that
subtracting a null character pointer from a pointer results in some
meaningful value, which is not guaranteed.  All you are guaranteed
to be able to do with ZERO is assign it and test for it.  Third,
this assumes that longs will always need to have the lower two
bits of their address cleared.  If you are going to make this silly
assumption, you might as well forget about the other attempts at
portability as you have already blown it.

> In general, casting pointers into (char*), casting (char*) back to
> the SAME TYPE of pointer,
 
Maybe yes, maybe no.

> taking the difference between two pointers of the SAME TYPE,

By definition, this is so.

> and adding an integral amount to a pointer are all safe operations.

Provided that you stay within the declared data type (i.e...
	char	foo[100];
	char	*goo;

	goo = foo;
	goo += 100;

Is not guaranteed to work.

-Ron



More information about the Comp.lang.c mailing list