Re: brain teasers



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.
.



Relevant Pages