Determing alignment of (char *) pointer

Ron Newman newman at mit-trillian.MIT.EDU
Fri Dec 5 12:05:39 AEST 1986


I am using a (char *) pointer to store a sequence of differently-typed
and differently-sized objects.  I want to make sure that each object
will be properly aligned before storing it.

In particular, I need to determine whether the pointer is 32-bit
aligned before attempting to store a long by casting it to a (long *).
Which is a better, more portable way of determining whether a pointer
is aligned?

   char *p;

   /* method 1 */

   if ((long)p & 3) ...


   /* method 2 */

   if ((long)(p - (char *) 0) & 3) ...


or if neither of these is best, what is better?

/Ron Newman



More information about the Comp.lang.c mailing list