Determing alignment of (char *) pointer

rbutterworth at watmath.UUCP rbutterworth at watmath.UUCP
Sat Dec 6 01:15:30 AEST 1986


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.)

Method 1 is definitely not reliable.  First, there is no guarantee
that a (long) can hold a (char*); some machines have pointers that
are longer than longs (e.g. one word for the word address, a second
word for the bit or byte offset).  Second, even if it does fit, there
is no guarantee that the pointer looks anything like an integer.  I
use a machine in which the upper 18 bits are the word address of the
object and the lower 18 bits contain the byte offset.  This byte
offset is NOT right justified, so the lower few bits will always
be zero and your test will always fail.

In general, casting pointers into (char*), casting (char*) back to
the SAME TYPE of pointer, taking the difference between two pointers
of the SAME TYPE, and adding an integral amount to a pointer are
all safe operations.  If you find you are making other kinds of
casts or arithmetic operations, there is a good chance that what
you are doing won't be portable.



More information about the Comp.lang.c mailing list