Olufowobi Lawal <wolex...@...> wrote:
>
> ! clarifying earlier post
>
> The swaps below shows wrong ways pple have tried to swap,
> the only correct one is swapgen(for generic) and swap.
swapgen is not correct.
>
> /*CORRECT SWAPS*/
>
>
> void swapgen(void *a, void *b, size_t size)
> {
> //generic way, notice the third argument
> char *ca, *cb;
You should use unsigned char. Plain char may be signed and
potentially use sign-magnitude or one's complement, in
which case certain representations when read, may result in
a different valued byte being written. [For example a
negative zero may be written as a normal zero byte.]
> int i;
An int needn't be big enough to scan the range of size_t.
[Consider if INT_MAX is 32767 and a and b point to structs
larger than 32767 bytes.]
> ca = (char *)a;
> cb = (char *)b;
> for(i=0;i<size;*(ca+i)^=*(cb+i),*(cb+i)^=*(ca+i),*(ca+i)^=*(cb+i),++i);
> }
void swapgen(void *s, void *t, size_t z)
{
unsigned char *us = s;
unsigned char *ut = t;
unsigned char uc;
while (z--)
{
uc = *us;
*us++ = *ut;
*ut++ = uc;
}
}
...
> /* WRONG SWAPS BELOW **/
...
> void swap1(void **x, void **y) {
> void *t = *x;
> *x = *y;
> *y = t;
> }
This will correctly swap two void * objects, viz...
void swap1(void **x, void **y) {
void *t = *x;
*x = *y;
*y = t;
}
#include <stdio.h>
int main(void)
{
void *a = "World\n";
void *b = "Hello ";
swap1(&a, &b);
fputs(a, stdout);
fputs(b, stdout);
return 0;
}
Of course, it can't be used portably if a and b are pointers
to anything other than a void or character type.
--
Peter