Reputation: 4694
I found the following declaration for a generic swap function in an answer on stackoverflow.
#define swap(x,y) do \
{ unsigned char swap_temp[sizeof(x) == sizeof(y) ? (signed)sizeof(x) : -1]; \
memcpy(swap_temp,&y,sizeof(x)); \
memcpy(&y,&x, sizeof(x)); \
memcpy(&x,swap_temp,sizeof(x)); \
} while(0)
However if we write a similar function in C it does not work and we need to pass in the size of the void* types explicitly for it to work. I understand that this would be happening because the macro would be expanded within the function from which it is called and sizeof would work since it would be in the same scope as the variable x or y. Am I correct?
If I am. Consider the following situation.
void someComplexFunction(void* a, void* b){
swap(a,b);
}
Is this right? I tried it and it worked. Why is this working?
Upvotes: 1
Views: 80
Reputation: 10940
your swapping the addresses of your pointers but not the actual content.
this code shows it
char *foo = "foo";
char *bar = "bar";
printf("before swap\n");
printf("foo address '%08x', foo content '%s'\n", foo, foo);
printf("foo address '%08x', foo content '%s'\n", bar, bar);
swap(foo, bar);
printf("after swap\n");
printf("foo address '%08x', foo content '%s'\n", foo, foo);
printf("foo address '%08x', foo content '%s'\n", bar, bar);
output is similar to this
before swap
foo address '010e58a8', foo content 'foo'
foo address '010e58ac', foo content 'bar'
after swap
foo address '010e58ac', foo content 'bar'
foo address '010e58a8', foo content 'foo'
Upvotes: 1