Implementing a generic swap function
What you'll learn: How to use void* and memcpy to exchange the data of two variables regardless of their data type.
The problem with specific swaps
In C, a standard swap function for integers requires int* parameters. If you want to swap doubles, you need a new function. If you want to swap custom structs, you need another. This leads to repetitive code. To solve this, we use the void* (a pointer to "raw" memory) and the memcpy function from <string.h> to move data at the byte level.
Thinking like a mover
Imagine you are a professional mover. You don't care if a box contains books, clothes, or kitchenware; you only care about how big the box is. If you have two spots of the same size, you can swap the items as long as you have a temporary "holding area" to put one item down while you move the other.
In C, the "box" is a memory address (void*), and the "size" is the number of bytes the data occupies (size_t).
The Generic Swap Code
To swap any two items, we treat them as arrays of bytes. We copy the bytes of the first item into a temporary buffer, copy the second into the first, and finally move the temporary buffer into the second.
#include <stdio.h>
#include <string.h> // Required for memcpy
void generic_swap(void *a, void *b, size_t size) {
// Create a temporary buffer (a byte array) to hold the data
char temp[size];
// 1. Copy 'a' into temp
memcpy(temp, a, size);
// 2. Copy 'b' into 'a'
memcpy(a, b, size);
// 3. Copy temp into 'b'
memcpy(b, temp, size);
}
int main() {
int x = 10, y = 20;
double p = 3.14, q = 2.71;
// We must pass the address and the size of the type
generic_swap(&x, &y, sizeof(int));
generic_swap(&p, &q, sizeof(double));
printf("x: %d, y: %d\n", x, y);
printf("p: %.2f, q: %.2f\n", p, q);
return 0;
}
How it works
By using void*, we tell the compiler: "I'm going to give you a memory address, but don't worry about what type of data is stored there yet." By passing sizeof(type), we tell the function exactly how many bytes to grab. The memcpy function then performs a "shallow copy" of that memory, effectively swapping the contents without the function ever needing to know if it's handling an integer, a float, or a complex object.
Key takeaway
Generic logic in C relies on void* to handle addresses and size_t to define the boundaries of the raw data being manipulated.