pointers-memory · beginner · ~15 min
Perform generic type-agnostic memory manipulation by treating pointers as raw byte sequences.
In dynamically typed languages, swapping variables is trivial. In C, generic swapping across arbitrary data types requires swapping raw memory byte-by-byte through unsigned char* pointers.
Implement:
void generic_swap(void *a, void *b, size_t size);
Swap size bytes between memory addresses a and b.
a == NULL, b == NULL, a == b, or size == 0, do nothing.unsigned char* and swap all size bytes in place.int x = 10, y = 20;
generic_swap(&x, &y, sizeof(int)); // x is now 20, y is now 10
double d1 = 3.14, d2 = 2.71;
generic_swap(&d1, &d2, sizeof(double)); // d1 is now 2.71, d2 is now 3.14
a, b: generic memory pointers; size: byte length to swap.
Modifies memory at a and b in place.
C11 freestanding. Swap byte-by-byte.
#include <stddef.h>
/* Swap size bytes between memory locations a and b. */
void generic_swap(void *a, void *b, size_t size) {
(void)a; (void)b; (void)size;
}
Allocating dynamic memory for temporary buffer; sign-extending signed char during swap.
a == b does nothing; size == 0 does nothing; NULL pointers do nothing.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.