Brain Teaser

Chris Calabrese cjc at ulysses.att.com
Thu Mar 29 08:38:38 AEST 1990


In article <99 at demott.COM>, kdq at demott.COM (Kevin D. Quitt) writes:
> In article <MCDANIEL.90Mar27200111 at rollmops.amara.uucp> mcdaniel at amara.uucp (Tim McDaniel) writes:
| >
| >>oesterle at wpi.wpi.edu (Shawn H. Oesterle) asks how to swap two pointers
| >>without using a third pointer.
| >
| >You can't do portably swap arbitrary legal pointer values without
| >using an intermediate variable.  In short, "no".
| 					     ????????????
| 
| (God, I love it when people say things are impossible (:-{>}  )
| 
|     I originally just mailed the answer, since I didn't want to clutter the
| net.  However...
| 
| 
| void swap_pointers( x, y )
| 
| long *x, *y;			/* whichever declaration is required */
|    {
|     *x	^= *y;
|     *y	^= *x;
|     *x	^= *y;
|    }
| 
| 
|     Or you can do it in-line.  (Seems silly to do it either way, but
| this *is* a puzzle, not a request for practical code).  Note that this
| technique can actually be used to exchange two (presumably large)
| strings - it's insensitive to data type or contents, and cannot cause
| overflow or any other error condition that wouldn't happen by reading or
| writing the same locations. 
| 
|     Disclaimer: This assumes that pointers are not longer than longs (or
| some other defined type).  On the other hand, how many machines do you
| know that have longer addresses than data? 

NO, NO, NO, NO, NO!!!
This only works on machines where a pointer is a simple number!!!
It doesn't work on machines with segmented architecture (intel, etc).
And, it doesn't work on machines with different sized pointers for
different types of pointers (Dual 86/80?).
-- 
Name:			Christopher J. Calabrese
Brain loaned to:	AT&T Bell Laboratories, Murray Hill, NJ
att!ulysses!cjc		cjc at ulysses.att.com
Obligatory Quote:	``Anyone who would tell you that would also try and sell you the Brooklyn Bridge.''



More information about the Comp.lang.c mailing list