Reverse a String in C Using Pointers – Three Approaches with Code

Reversing a string in C means rearranging its characters so the last character becomes the first and vice versa: "Hello" becomes "olleH". The standard technique is the two-pointer swap — place one pointer at the start and one at the end, swap the characters they point to, then move the pointers toward each other until they meet. This page shows three approaches: pointer arithmetic (in-place), array indexing (in-place), and a copy-to-buffer method that preserves the original.

The original post used gets() (removed from C11 due to buffer overflow) and void main(). Both are fixed here.

How the Two-Pointer Reversal Works

For the string "Hello" (5 characters):

Step left right Swap String state
Start H (index 0) o (index 4) H ↔ o oellH
1 e (index 1) l (index 3) e ↔ l olleH
2 l (index 2) l (index 2) left == right → stop olleH ✓

For a string of length n, only n/2 swaps are needed. The middle character (if n is odd) is never moved — it is already in position.

C Program: Reverse a String (Three Approaches)

/* Reverse a string in C — three approaches
 * Compile: gcc -ansi -Wall -Wextra revstr.c -o revstr */
#include <stdio.h>
#include <string.h>

/* Approach 1: two-pointer in-place using pointer arithmetic */
void reverse_ptr(char *s)
{
    char *left  = s;
    char *right = s + strlen(s) - 1;
    char tmp;
    while (left < right) {
        tmp    = *left;
        *left  = *right;
        *right = tmp;
        left++;
        right--;
    }
}

/* Approach 2: index-based in-place */
void reverse_idx(char *s)
{
    int left  = 0;
    int right = (int)strlen(s) - 1;
    char tmp;
    while (left < right) {
        tmp      = s[left];
        s[left]  = s[right];
        s[right] = tmp;
        left++;
        right--;
    }
}

/* Approach 3: reverse into a new buffer — original unchanged */
void reverse_copy(const char *src, char *dst)
{
    int n = (int)strlen(src);
    int i;
    for (i = 0; i < n; i++)
        dst[i] = src[n - 1 - i];
    dst[n] = '\0';
}

int main(void)
{
    char original[256], copy[256], result[256];

    printf("Enter a string: ");
    if (fgets(original, sizeof(original), stdin) == NULL) return 1;
    original[strcspn(original, "\n")] = '\0';   /* strip trailing newline */

    strcpy(copy, original);
    reverse_ptr(copy);
    printf("Reversed (pointer):  %s\n", copy);

    strcpy(copy, original);
    reverse_idx(copy);
    printf("Reversed (index):    %s\n", copy);

    reverse_copy(original, result);
    printf("Reversed (copy):     %s\n", result);
    printf("Original unchanged:  %s\n", original);

    return 0;
}

How to Compile and Run

gcc -ansi -Wall -Wextra revstr.c -o revstr
./revstr

Sample Output

Enter a string: Hello World
Reversed (pointer):  dlroW olleH
Reversed (index):    dlroW olleH
Reversed (copy):     dlroW olleH
Original unchanged:  Hello World

Enter a string: C Programming
Reversed (pointer):  gnimmargorP C
Reversed (index):    gnimmargorP C
Reversed (copy):     gnimmargorP C
Original unchanged:  C Programming

Code Explanation

  • Pointer approach: char *left = s; char *right = s + strlen(s) - 1;s is already a pointer to the first character. Adding strlen(s) - 1 moves it to the last character (the one before the null terminator '\0'). The while (left < right) condition stops exactly when the pointers meet or cross — it handles both even-length strings (pointers meet at the gap between the two middle characters) and odd-length strings (left == right at the middle character, no swap needed).
  • Why the index and pointer approaches are equivalent: s[i] and *(s+i) are identical in C — both access the character i positions from the start of the array. The index approach is easier to read; the pointer approach is the form you are most likely to encounter in interview questions and library source code.
  • Copy approach: dst[i] = src[n - 1 - i] — when i=0, this copies src[n-1] (last character) to dst[0] (first position). When i=n-1, it copies src[0] (first character) to dst[n-1]. The explicit dst[n] = '\0' is mandatory — without it the destination buffer is not null-terminated and functions like printf("%s") will read past the end of the string.
  • fgets and strcspn: fgets stores the trailing newline in the buffer (unlike scanf("%s")). strcspn(original, "\n") returns the index of the first newline; setting that position to '\0' strips it cleanly. This replaces the old gets() call which had no buffer-size limit.
  • Why const char *src in reverse_copy: The copy function reads but never modifies src. Marking it const makes this intent explicit and allows passing string literals (which live in read-only memory) safely. Omitting const would cause a compiler warning when passing a const string to the function.

Comparison of the Three Approaches

Approach Modifies original? Extra memory Requires string.h
Two-pointer (pointer) Yes (in-place) O(1) — one char strlen() only
Two-pointer (index) Yes (in-place) O(1) — one char strlen() only
Copy to buffer No O(n) — second buffer strlen() only

What This Program Teaches

  • Pointer arithmetic on strings: A string in C is a char array. A pointer to a string is a pointer to its first character. Adding an integer to a pointer moves it forward by that many characters. This makes s + strlen(s) - 1 a natural way to point to the last character.
  • The two-pointer pattern: Start from both ends, converge toward the middle. This same idea appears in palindrome checking, two-sum on a sorted array, and partition operations in quicksort. Recognizing it as a pattern makes all of these easier.
  • Null terminator discipline: Any time you build a string manually (by copying characters into a buffer), you must append '\0' at the end. Forgetting it causes undefined behavior — the string functions have no other way to know where the string ends.

Frequently Asked Questions

How do you reverse a string in C without using string.h?

Replace strlen() with a manual length computation: int n = 0; while (s[n]) n++;. Then apply the two-pointer swap with left = 0; right = n - 1;. The reversal loop itself uses only array indexing — no string functions required.

Does the two-pointer approach work for strings with spaces?

Yes. Spaces are ordinary characters (ASCII 32). The two-pointer swap treats them the same as letters. “Hello World” reverses to “dlroW olleH” — the space moves from index 5 to index 5 (it stays in the middle of the reversed result, as verified in the sample output above).

What happens when you reverse an empty string or single-character string?

Empty string: strlen("") returns 0, so right = s + 0 - 1 points before the start of the array. The while (left < right) condition is immediately false (left == s, right == s – 1), so the loop never executes. The string is unchanged — correct. Single character: left and right both point to the same character; the condition left < right is false, so no swap occurs. Also correct.

Related Programs

Recommended book:
The C Programming Language — Kernighan & Ritchie (India) |
(US)
 | 
C Programming: A Modern Approach — K.N. King (India) |
(US)

Test your understanding: C Aptitude Questions — or try our C Programming Quiz App on Android.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>