Example 1 — A generic swap
Swap any two objects of equal size, byte by byte.
#include <stdio.h>
static void swap_any(void *a, void *b, size_t n) {
unsigned char *x = a, *y = b;
while (n--) {
unsigned char t = *x;
*x++ = *y;
*y++ = t;
}
}
int main(void) {
int i = 1, j = 2;
double d = 1.5, e = 2.5;
swap_any(&i, &j, sizeof i);
swap_any(&d, &e, sizeof d);
printf("i=%d j=%d\n", i, j);
printf("d=%.1f e=%.1f\n", d, e);
return 0;
} How It Works
void *parameters accept the address of any type.- Casting to
unsigned char *allows byte-wise access. - The caller supplies the object size.
