Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
swapping variables
#23
Orit Wrote:What? You don't need to split anything. In C, you'd code something like:

Code:
char *p,*q;
for (p=a, q=b; *p != '\0' && *q != '\0'; p++, q++)
{
  *p ^= *q;
  *q ^= *p;
  *p ^= *q;
}
/* add the tail of the (previously) longer string onto the shorter.
    This assumes there was enough room for it there.
    If there wasn't, we shouldn't be attempting to swap anyway,
    as new memory would need to be allocated.
*/
if ((*p == '\0') && (*q != '\0'))
{
  strcpy(q,p);
  *q = '\0';
}
else if ((*p != '\0') && (*q == '\0')
{
  strcpy(p,q);
  *p = '\0';
}

Obviously this is not very human-readable. It's only one step removed from assembly language.

When I need to swap strings, I would just swap the address of the pointers instead of swapping the array itself.

if *p points to the first string and *q points to the 2nd string, swap p and q around and they're effectively the same as swapping values irrespective of the size of the string.

BTW, xor is exclusive OR, ie either this or that, but not both and not none.
Reply


Messages In This Thread
swapping variables - by GummyBear - 2008-10-24, 02:58 AM
swapping variables - by loddlaen - 2008-10-24, 03:02 AM
swapping variables - by Fiel - 2008-10-24, 03:05 AM
swapping variables - by Stereo - 2008-10-24, 09:32 AM
swapping variables - by GummyBear - 2008-10-27, 12:29 AM
swapping variables - by Horusmaster - 2008-10-27, 12:39 AM
swapping variables - by Russt - 2008-10-27, 01:36 AM
swapping variables - by Horusmaster - 2008-10-27, 02:00 AM
swapping variables - by Russt - 2008-10-27, 02:02 AM
swapping variables - by Horusmaster - 2008-10-27, 02:07 AM
swapping variables - by Nikkey - 2008-10-27, 02:15 AM
swapping variables - by Russt - 2008-10-27, 02:21 AM
swapping variables - by Orit - 2008-10-27, 02:54 AM
swapping variables - by Nikkey - 2008-10-27, 04:51 AM
swapping variables - by Stereo - 2008-10-27, 07:53 AM
swapping variables - by Orit - 2008-10-27, 09:21 AM
swapping variables - by Nikkey - 2008-10-27, 10:17 AM
swapping variables - by Orit - 2008-10-27, 10:49 AM
swapping variables - by Nikkey - 2008-10-27, 11:59 AM
swapping variables - by Devil - 2008-10-27, 12:03 PM
swapping variables - by Orit - 2008-10-27, 12:18 PM
swapping variables - by Nikkey - 2008-10-27, 12:18 PM
swapping variables - by GummyBear - 2008-10-27, 07:33 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)