Reputation: 2051
I'm attempting to swap two values of any given type by swapping their pointers' addresses.
The function I've come up with works fine when called for any two integers, but behaves strangely (to me at least) when more integers are defined in the same scope. For example, consider this SSCCE:
#include <stdio.h>
static inline void exchx(void** a, void** b) { void* p = *a; *a = *b; *b = p; }
int main(void) {
int a = 1;
int b = 2;
int c = 3;
int d = 4;
printf("\nBefore: abcd = %d, %d, %d, %d", a, b, c, d);
exchx((void**)&a,(void**)&b);
printf("\nAfter: abcd = %d, %d, %d, %d\n", a, b, c, d);
}
I would expect the second print to be "2, 1, 3, 4", but I get this instead:
Before: abcd = 1, 2, 3, 4
After: abcd = 2, 1, 2, 4
I'm sure there are much saner ways to swap data - that is not the question at all - I'm just curious about this behavior. Any ideas?
Upvotes: 1
Views: 293
Reputation:
In your code, this line
exchx((void**)&a,(void**)&b);
casts a pointer to int to a pointer to pointer of void. This just means your int
gets interpreted as if it were a pointer. Expect any strange behaviour doing this.
In short, your exchx
function is fine for exchanging actual pointers ... not for whatever else.
Upvotes: 5