Turning Learners Into Developers
Codekilla
CODEKILLA
C · beginner

Reverse a String In-Place (C)

Reverse a null-terminated C string in place using O(1) extra memory — a classic pointer/array exercise.

← Coding Challenges

Problem

Write a function that reverses a null-terminated C string in place — no new buffer, no malloc.

c
void reverse(char *s);

char str[] = "hello";
reverse(str);
puts(str);   // "olleh"

Two-pointer swap

c
#include <string.h>

void reverse(char *s) {
    if (!s) return;
    size_t n = strlen(s);
    if (n < 2) return;
    size_t i = 0, j = n - 1;
    while (i < j) {
        char tmp = s[i];
        s[i++]   = s[j];
        s[j--]   = tmp;
    }
}

XOR swap variant (no temp variable — just to show off)

c
while (i < j) {
    s[i] ^= s[j];
    s[j] ^= s[i];
    s[i] ^= s[j];
    i++; j--;
}

Don't actually use XOR swap in production:

  • Same compiler output as the temp-variable version after optimisation.
  • Fails if i == j (XORs a byte with itself = 0).
  • Harder to read.

What interviewers look for

  • Two-pointer technique (left index walks up, right index walks down).
  • Null-pointer and empty-string handling.
  • O(n/2) ≈ O(n) time, O(1) extra space.
  • Awareness that strlen is O(n) — call it once, cache the result.

Variation — reverse only words

"Hello world" → "world Hello":

  1. Reverse the whole string → "dlrow olleH".
  2. Reverse each word individually → "world Hello".

Variation — Unicode (UTF-8) reversal

Reversing bytes corrupts multi-byte characters. Walk the string by code-point first, then swap whole code-points. Standard library doesn't do this — use ICU or a dedicated UTF-8 library.