Re: brain teasers
- From: Richard Heathfield <rjh@xxxxxxxxxxxxxxx>
- Date: Thu, 05 Apr 2007 06:04:19 +0000
Daniel Rudy said:
<snip>
#define MAXSWAP 32 /* maximum size of variable swap */
int swap(void *a, void *b, int size)
{
char temp[MAXSWAP]; /* temp buffer */
if (size > MAXSWAP) return(-1);
memcpy(temp, a, size);
memcpy(a, b, size);
memcpy(b, temp, size);
return(0);
}
Now what's wrong with that?
Not very much. Here's a less restrictive solution:
#include <string.h>
#define MAXSWAP 32
void swap(void *va, void *vb, size_t size)
{
unsigned char *a = va;
unsigned char *b = vb;
unsigned char temp[MAXSWAP] = {0};
while(size >= MAXSWAP)
{
memcpy(temp, a, MAXSWAP);
memcpy(a, b, MAXSWAP);
memcpy(b, temp, MAXSWAP);
size -= MAXSWAP;
a += MAXSWAP;
b += MAXSWAP;
}
memcpy(temp, a, size);
memcpy(a, b, size);
memcpy(b, temp, size);
return;
}
It is possible that this could be done more elegantly (eliminating the
duplicated code). Given the time of day here, I'll leave that as an
exercise.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at the above domain, - www.
.
- Follow-Ups:
- Re: brain teasers
- From: CBFalconer
- Re: brain teasers
- References:
- brain teasers
- From: viv342
- Re: brain teasers
- From: Martin Ambuhl
- Re: brain teasers
- From: rohitjogya@xxxxxxxxx
- Re: brain teasers
- From: Martin Ambuhl
- Re: brain teasers
- From: Daniel Rudy
- brain teasers
- Prev by Date: Re: Memory leak when internal pointer passed out as parameter
- Next by Date: Re: Memory leak when internal pointer passed out as parameter
- Previous by thread: Re: brain teasers
- Next by thread: Re: brain teasers
- Index(es):
Relevant Pages
|