Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!watmath!rbutterworth From: rbutterworth@watmath.UUCP Newsgroups: comp.lang.c Subject: Re: Determing alignment of (char *) pointer Message-ID: <3798@watmath.UUCP> Date: Fri, 5-Dec-86 10:15:30 EST Article-I.D.: watmath.3798 Posted: Fri Dec 5 10:15:30 1986 Date-Received: Sat, 6-Dec-86 00:55:13 EST References: <1510@mit-trillian.MIT.EDU> Organization: U of Waterloo, Ontario Lines: 29 In article <1510@mit-trillian.MIT.EDU>, newman@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.