Simvik

Generic swap

Exchange two objects of any type, byte by byte. A medium embedded C problem (Pointers), run and graded in the browser.

medium · Pointers · void-pointer

Exchange the contents of the two objects at a and b, each size bytes long. The objects do not overlap.

The function knows nothing about the type, so it has to work on raw bytes. Variable-length arrays are not available; you do not need a buffer.

Starter code

void swap_any(void *a, void *b, size_t size) {
  // Exchange `size` bytes between the two objects.
}

Example tests

Two 32-bit values

uint32_t x = 0x11111111, y = 0x22222222;
swap_any(&x, &y, sizeof x);
printf("0x%08X 0x%08X\n", x, y);

Expected output:

0x22222222 0x11111111

Two structs

struct pair { int16_t a; int16_t b; } p = { 1, 2 }, q = { 3, 4 };
swap_any(&p, &q, sizeof p);
printf("%d %d %d %d\n", p.a, p.b, q.a, q.b);

Expected output:

3 4 1 2

Learn it first

  • Pointers · Addresses, arithmetic, const, void pointers and object lifetime.

More Pointers problems