basics · beginner · ~15 min

Reverse a string

Combine the two-pointer pattern with C strings.

Challenge

Reverse a C string in place, character by character.

Task

Implement void reverse(char *s) that reverses the NUL-terminated string s in place. No main — the grader calls it.

Input

A writable, NUL-terminated string s (may be empty).

Output

Nothing is returned. The characters of s are reversed; the string stays NUL-terminated.

Example

"hello"     ->   "olleh"
"ab"        ->   "ba"
"racecar"   ->   "racecar"

Edge cases

  • Empty string stays empty; guard so computing length - 1 does not underflow for size_t.
  • A single character is unchanged.

Rules

  • Reverse in place — do not allocate a new string.

Input format

A writable NUL-terminated string s.

Output format

Nothing returned; s is reversed in place.

Constraints

In place, no new allocation; handle the empty string safely.

Starter code

#include <string.h>

void reverse(char *s) {
    /* TODO */
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.