Path: utzoo!attcan!uunet!samsung!usc!srhqla!demott!kdq From: kdq@demott.COM (Kevin D. Quitt) Newsgroups: comp.lang.c Subject: Re: Brain Teaser Message-ID: <99@demott.COM> Date: 28 Mar 90 18:05:42 GMT References: Reply-To: kdq@demott.COM (Kevin D. Quitt) Organization: DeMott Electronics Co., Van Nuys CA Lines: 46 In article mcdaniel@amara.uucp (Tim McDaniel) writes: > >>oesterle@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? kdq -- Kevin D. Quitt Manager, Software Development DeMott Electronics Co. VOICE (818) 988-4975 14707 Keswick St. FAX (818) 997-1190 Van Nuys, CA 91405-1266 MODEM (818) 997-4496 Telebit PEP last 34 12 N 118 27 W srhqla!demott!kdq kdq@demott.com "Next time, Jack, write a God-damned memo!" - Jack Ryan - Hunt for Red October