Pointer Comparison and Portability

pinkas at mipos3.UUCP pinkas at mipos3.UUCP
Sat Feb 14 03:20:41 AEST 1987


In article <416 at vaxine.UUCP> nw at vaxine.UUCP (Neil Webber) writes:
>Consider the following C function:
>
>        same_char (p, q)
>        char *p;
>        char *q;
>        {
>                return (p == q);
>        }
>
>Does this function only return a non-zero value when p and q point
>to the same physical character?  This may seem like a silly question,
>but I haven't found an iron-clad answer in K & R yet.   I quote:
...
>It goes on to say that all bets are off for comparisons of pointers between
>different arrays.  Thus, if p and q pointed inside different character arrays,
>it would appear that comparison between those pointers, even for equality,
>is undefined.
...

True.  Consider the 80x86 achitecture and many of the existing C ompilers
for it.  Many of them try to optimize in memory models with large data
segments by using as small an offset as possible for the first element of
the array.  (This is a very small optimization, but it does save some
comparisons if the array is known to be smaller than a certain size.)  For
example:

	char p[16], q[16];

might let p = 0x1000:0000 and q = 0x1001:0000.  If your C compiler does not
do the necessary conversion to common segments, or a similar calculation,
the comparison will fail.  Many early C compiler for the 8086 treated
pointers as ints for comparison and long (segmented) pointers as longs.
Thus with the above example, the pointers would be considered to point to
objects 64k apart.  The proper calculation is (seg * sigsize + offset).  If
this calculation is used, the above arrays are 16 bytes apart (on the 8086
at least), and p[16] is identical (same location) as q[0].

Considering that K&R specically said that only pointers to the same array
should be compared, and the fact that many C compilers take K&R to be the
final word on everything, I would say that unless your compiler manual
states otherwise (or it works), you should avoid comparing pointers to
different arrays.

-Israel
-- 
User (n.): A programmer who will believe anything you tell him.

----------------------------------------------------------------------
UUCP:	{amdcad,decwrl,hplabs,oliveb,pur-ee,qantel}!intelca!mipos3!pinkas
ARPA:	pinkas%mipos3.intel.com at relay.cs.net
CSNET:	pinkas%mipos3.intel.com



More information about the Comp.lang.c mailing list