- How to place two pointers at opposite ends of a string
- Why swapping inward reverses the string in place, with no extra buffer
- How the loop condition
left < righthandles both odd and even lengths - Why you must not reverse a string literal
- The difference between reversing in place and reversing into a new buffer
How In-Place Reversal Works in Memory
Reversing a string means putting the characters in the opposite order: the first character becomes the last, the second becomes the second-last, and so on. The most space-efficient way to do this is in place — no second array needed. You place one pointer at the beginning, one at the end, and swap the characters they point at. Then both pointers move toward the middle, and you repeat. When they meet or cross, the whole string has been reversed.
This works because each swap fixes two characters in their final positions at once. The left pointer's character goes to the right, and the right pointer's character comes to the left — and neither will be touched again, since the pointers move inward. For a string of even length, the pointers cross after the last swap. For an odd length, they meet at the middle character, which is already in its correct position and needs no swap.
The critical constraint: the string must be modifiable. You can't reverse a string literal like "Hello", because it lives in read-only memory — attempting to write to it is undefined behaviour, usually a crash. You need a char array you own, either declared locally or allocated on the heap. This program uses an array so the reversal is safe.
💡 In one line: Reversal = swap the outermost characters, then the next-outermost, and so on, until the pointers meet in the middle.
The Three Steps of Reversal
| Step | Pointer operation | Effect |
|---|---|---|
| 1. Set up the pointers | left = s; right = s + len - 1; | left at first char, right at last char |
| 2. Swap while they haven't crossed | while (left < right) { swap(*left, *right); left++; right--; } | Outer characters are exchanged and the pointers move inward |
| 3. Done | — | The string is reversed in place; no terminator needs to be moved |
The condition left < right is the key. When the string has even length (say 6 characters), the pointers move inward: positions 0 and 5 are swapped, then 1 and 4, then 2 and 3. After that swap, left moves to 3 and right moves to 2 — now left > right, and the loop stops. When the string has odd length (say 7 characters), after three swaps the pointers both point at position 3 — the middle character — and left < right is false. The middle character is already in place, so no swap is needed. In both cases the loop terminates correctly.
Note that the null terminator is never touched. The reversal only swaps characters strictly between the first and last real characters. The terminator stays where it is, at the end of the buffer, which is exactly where it should be. This means the string remains a valid C string throughout and after the operation.
Complete C Program
Program: reverse a string in place using two pointers (implementation of strrev)
#include <stdio.h>
/* Return the length of a string without using strlen. */
size_t str_len(const char *s) {
const char *p = s;
while (*p != '\0') {
p++;
}
return (size_t)(p - s);
}
/* Reverse the string s in place. s must be a modifiable array. */
void str_reverse(char *s) {
if (s == NULL) {
return;
}
size_t len = str_len(s);
if (len < 2) {
return; /* empty string or single character: nothing to do */
}
char *left = s; /* first character */
char *right = s + len - 1; /* last real character, not the terminator */
/* Swap inward until the pointers meet or cross */
while (left < right) {
char temp = *left;
*left = *right;
*right = temp;
left++;
right--;
}
}
int main(void) {
/* Must be an array — string literals are read-only. */
char text[] = "Hello, World!";
printf("Before reverse:\n");
printf(" text = \"%s\"\n", text);
str_reverse(text);
printf("\nAfter reverse:\n");
printf(" text = \"%s\"\n", text);
/* Also demonstrate an odd-length string */
char word[] = "level";
printf("\nBefore reverse:\n");
printf(" word = \"%s\"\n", word);
str_reverse(word);
printf("After reverse:\n");
printf(" word = \"%s\"\n", word);
return 0;
}
Program Output
Before reverse:
text = "Hello, World!"
After reverse:
text = "!dlroW ,olleH"
Before reverse:
word = "level"
After reverse:
word = "level"
The first string reverses completely — thirteen characters, all exchanged. The second string is a palindrome: reversing "level" produces "level" again, because it reads the same forward and backward. That's a useful property to see in action: the reversal algorithm doesn't know or care whether the result happens to equal the input; it just does its swaps. You can verify the palindrome property by comparing the string to its reverse — a common follow-up exercise.
Step-by-Step Explanation
Let's trace the pointers through memory.
1. Setup
text is a char array of 14 bytes: 'H','e','l','l','o',',',' ','W','o','r','l','d','!','\0'. The array has 13 real characters and a terminator. Because it was declared as an array and initialized with a string literal, the compiler allocates space for the full string plus the terminator, and it's writable — unlike a string literal pointer.
2. Find the length
str_len walks a pointer p from the start until it hits '\0'. It then subtracts the original address from p to get the length. For text, that's 13. This is the same pointer-difference trick used in the length program (assignment 5): pointer subtraction gives the number of elements between two addresses.
3. Place the pointers
left starts at s, pointing at 'H'. right starts at s + 13 - 1 = s + 12, pointing at '!'. If right had been set to s + len it would point at the terminator — swapping with the terminator would corrupt the string. Setting it to s + len - 1 is essential: the last real character is one before the terminator.
4. The swap loop
The loop runs while left < right. Each iteration swaps the characters, then moves both pointers inward. Let's trace the first few swaps on "Hello, World!":
- Iteration 1:
*left = 'H',*right = '!'. Swap → string becomes"!ello, WorldH".leftadvances to index 1,rightmoves to index 11. - Iteration 2:
*left = 'e',*right = 'd'. Swap →"!dllo, WorleH". Pointers move to indices 2 and 10. - Iteration 3:
*left = 'l',*right = 'l'. Swap → no visible change (same character), but the pointers still move inward. Indices 3 and 9. - Iteration 4:
*left = 'l',*right = 'r'. Swap →"!dlro, WolleH". Indices 4 and 8. - Iteration 5:
*left = 'o',*right = 'o'. Swap → no change. Indices 5 and 7. - Iteration 6:
*left = ',',*right = ' '. Swap →"!dlroW ,olleH".leftbecomes 6,rightbecomes 6. Nowleft < rightis false.
The loop exits. The string is "!dlroW ,olleH" — exactly the reverse of the original. Six swaps, six pairs of characters exchanged, thirteen characters reversed. (The character at index 6 — the comma — was the middle character of the original string? No, the middle of a 13-character string is index 6, which is ' ' in the original, then after the last swap it becomes ','. Either way, it ends up in the correct final position and doesn't need its own swap.)
5. Even-length strings
For a string like "abcd", length 4: left = 0, right = 3. Swap 'a' and 'd' → "dbca". left = 1, right = 2. Swap 'b' and 'c' → "dcba". left = 2, right = 1. Now left < right is false, loop exits. Two swaps, four characters reversed. The pointers crossed rather than met — no middle character existed because the length is even.
6. Single character and empty string
The guard if (len < 2) return; handles both. For an empty string, there's nothing to reverse. For a single character, the first and last characters are the same, so no swap is needed. Without this guard, the loop wouldn't execute anyway (since left == right for length 1), but the guard makes the intent explicit and avoids computing right = s + 0 in a way that might look suspicious. It's defensive but also clearer.
7. Why must text be an array?
String literals live in read-only memory. If you write char *p = "Hello"; and then try to reverse it with this function, the pointer p is valid but the memory it points at is read-only — writing to it is undefined behaviour, usually a segfault. The declaration char text[] = "Hello, World!"; is different: the compiler creates a writable array and copies the literal into it. Now the pointer text points at that array, and the reverse function can modify it safely. This is a critical distinction that trips up many beginners.
8. Why no terminator handling?
Because the reversal never touches the terminator. The right pointer starts one before it, and the loop stops when left reaches or passes right. The terminator stays at index 13, exactly where it was. After the reversal, the string is still a valid C string — same length, same terminator, different character order.
9. Alternative: reverse into a new buffer
In-place reversal is efficient (O(1) extra space), but it modifies the input. If you need to keep the original and produce a reversed copy, you need a second buffer of the same length. Walk src from start to end while writing characters backward into dest:
char *src = original;
char *dst = reversed + len - 1;
while (*src) {
*dst-- = *src++;
}
reversed[len] = '\0';
This writes characters in reverse order but doesn't touch the original. It requires O(n) extra space, but preserves the input. Which approach is appropriate depends on whether the caller wants the string modified in place or wants a copy.
10. Recursive reversal
Reversal can also be written recursively: swap the first and last characters, then recurse on the substring between them. The base case is when the substring has length 0 or 1. It's elegant but uses O(n) stack space for the recursion, and the iterative version is generally clearer and faster. The recursive version is sometimes used as an interview exercise, but the in-place two-pointer loop is the standard production approach.
11. Does this work for Unicode?
Only for single-byte encodings like ASCII or Latin-1. A UTF-8 string uses multiple bytes per character for anything beyond ASCII — reversing the bytes would break those multi-byte characters, producing mojibake. Proper UTF-8 reversal needs to walk character boundaries, not bytes. For C beginners, ASCII is the common case and the program is correct for it; for production code handling international text, use a Unicode-aware library.
12. Complexity
The loop does n/2 swaps, each O(1). Total time is O(n), where n is the string length. Extra space is O(1) — just three pointers and a temporary char. This is optimal for in-place reversal. The function is also stable and side-effect-free beyond modifying the input buffer, making it easy to test and reason about.
🎯 Remember this: Reversal swaps outward characters inward until the pointers meet or cross. The loop condition left < right handles both odd and even lengths correctly, and the terminator is never touched. And never try to reverse a string literal — you need a writable array.
Frequently Asked Questions
1. Why not just use strrev?
strrev is not part of the C standard library — it exists in some compilers (like MSVC) but not all. Relying on it makes your code non-portable. This exercise teaches you how it works so that you can write it yourself and understand the underlying pointer mechanics. The implementation is short enough that having your own version is often preferable.
2. Why does my program crash when I reverse a string literal?
Because string literals are stored in read-only memory. If you write char *s = "Hello"; str_reverse(s);, the pointer is valid but the memory it points at cannot be written — attempting to write is undefined behaviour, and most platforms enforce this with a segfault. Use a writable array instead: char s[] = "Hello";. The array is initialized from the literal but lives in writable memory, so reversal is safe.
3. Can I reverse a string without finding its length first?
You need to know where the last character is. One option is to walk a pointer to the end of the string first — that's effectively computing the length. Another is to use recursion, which doesn't explicitly compute length but uses the call stack to remember positions. The two-pointer approach requires the length or a pre-positioned right pointer; there's no way around knowing where the end is.
4. Does this work for strings with spaces or punctuation?
Yes. The function operates on raw char values and doesn't care what they represent. Spaces, commas, digits, punctuation — all are treated as characters and reversed along with everything else. The example "Hello, World!" contains both a space and punctuation, and the result "!dlroW ,olleH" confirms that everything was reversed.
5. How do I reverse only part of a string?
Pass the start and end pointers of the range you want to reverse. The loop logic is identical — just begin with left at the range's start and right at the range's end (minus one). This is useful for reversing words within a sentence while keeping word order intact: first reverse the whole sentence, then reverse each word individually. That's how many "reverse words in a sentence" interview problems are solved.
6. What is the time and space complexity?
Time is O(n) where n is the string length — each character is visited at most once, and each swap handles two characters. Space is O(1) — only a few pointer variables and one temporary char, regardless of string length. This is optimal for in-place reversal. A new-buffer approach would use O(n) extra space; the recursive version uses O(n) stack space. The iterative in-place version is the most efficient in both dimensions.
💡 Tip: Once this works, try reversing the words in a sentence without reversing the characters within each word. For "Hello, World!", the output should be "World!, Hello," — not "!dlroW ,olleH". The classic approach: reverse the whole string first, then reverse each word individually. Same pointer technique, applied on substrings.