Skip to main content

ft_strrev — Reverse a String In-Place

Allowed functions: none

Write a function that reverses (in-place) a string. It must return its parameter.

char    *ft_strrev(char *str);

Solution

Download ft_strrev.c
char *ft_strrev(char *str) {

int len = 0;
int i = 0;
char tmp;

while (str[len])
len++;

while (i < len / 2) {
tmp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = tmp;

i++;
}

return str;
}

How It Works

Goal: Reverse a string in-place and return it.

Approach: Swap characters from both ends of the string, moving inward until the pointers meet in the middle.

Step by step:

  1. Calculate the string length by iterating to the null terminator.
  2. Loop with index i from 0 to len / 2.
  3. On each iteration, swap str[i] with str[len - 1 - i] using a temporary variable.
  4. Return the now-reversed string.

Key concept: In-place reversal using a two-index swap technique, requiring only one extra byte of memory (the tmp variable).