- How strings are stored in C — as arrays of characters, terminated by
'\0' - How
strlen()determines the length without the null terminator - How to reverse a string in place using two pointers
- How to reverse a string by building a new copy
- Why
char *parameters can modify the caller's string (pass by reference)
What "reversing a string" actually means
In C, a string isn't a first-class type — it's a sequence of characters in memory, ending with a special character '\0' (the null terminator). So the string "hello" occupies 6 bytes of memory: 'h', 'e', 'l', 'l', 'o', and the final '\0'. When we say a string has length 5, we mean there are 5 visible characters before the null terminator. The terminator itself doesn't count.
Reversing a string means swapping the first character with the last, the second with the second-to-last, and so on, until you reach the middle. For "hello", the result is "olleh". The null terminator stays at the end — it's not part of the reverse, because it's not a visible character. This is the key insight that makes the reversal algorithm work: you swap characters at symmetric positions, ignoring the terminator.
There are two ways to implement this. The in-place approach modifies the original string directly — it swaps characters in the caller's array, so when the function returns, the caller's string is now reversed. The copy approach creates a new string and returns it, leaving the original untouched. Both are useful, but for different purposes: in-place is more memory-efficient and is what most implementations use, while the copy approach is needed if you want to preserve the original.
C doesn't have a standard strrev() function — it's a non-standard extension in some compilers (like MSVC's _strrev), but not portable. Writing your own is a common exercise, and it teaches an important lesson about how C strings work: they're mutable arrays, not immutable values. Passing a char * to a function lets the function modify the underlying bytes.
💡 In one line: find the length n = strlen(s), then swap s[left] with s[right] for left from 0 and right from n-1, moving inward until they meet. The string is reversed in place.
Two approaches: in-place vs. new copy
Before writing the code, decide which style you want. Each has its own signature and its own tradeoffs:
| Approach | Signature | Tradeoffs |
|---|---|---|
| In-place | void reverseString(char *s) | Modifies the caller's string. No allocation. Fastest. Caller must own a mutable buffer. |
| New copy | char *reversedCopy(const char *s) | Allocates a new buffer. Original preserved. Caller must free the result. Safer for read-only input. |
The in-place version is the more common exercise, and it's the one we'll focus on. The prototype:
void reverseString(char *s);
And the definition, using two pointers:
void reverseString(char *s) {
int n = strlen(s);
int left = 0;
int right = n - 1;
while (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
The while (left < right) condition is what stops the loop. When left and right meet (for odd-length strings) or cross (for even-length strings), all pairs have been swapped, and the string is fully reversed. The condition left < right (strict) ensures we don't swap the middle character with itself, which would be harmless but pointless.
For the copy version, the signature changes and you have to allocate memory:
char *reversedCopy(const char *s) {
int n = strlen(s);
char *out = malloc(n + 1); /* +1 for '\0' */
if (!out) return NULL;
for (int i = 0; i < n; i++) {
out[i] = s[n - 1 - i];
}
out[n] = '\0';
return out;
}
The const char * parameter tells the compiler (and the reader) that this function won't modify the input. The malloc(n + 1) allocates space for the reversed characters plus the null terminator. The out[i] = s[n - 1 - i] line does the reversing: character i of the output is character n - 1 - i of the input. Finally, out[n] = '\0' terminates the new string.
The caller of the copy version must free the returned pointer: char *r = reversedCopy("hello"); ...; free(r);. Forget to free, and you have a memory leak. Use-after-free, and you have undefined behavior. This is why the in-place version is often preferred — no memory management, no leaks, no dangling pointers. The copy version is only worth it when you need to preserve the original.
🎯 Key idea: the two-pointer swap works because C strings are mutable arrays. If the input is a string literal (e.g., reverseString("hello")), the behavior is undefined — string literals are read-only. Always pass a modifiable buffer, like a char array.
Complete C Program
Program: reverse a string in place
#include <stdio.h>
#include <string.h>
/* Function prototype */
void reverseString(char *s);
int main(void) {
char buffer[100];
printf("Enter a string: ");
if (scanf("%99s", buffer) != 1) {
printf("No input.\n");
return 1;
}
printf("Original: %s\n", buffer);
reverseString(buffer);
printf("Reversed: %s\n", buffer);
return 0;
}
/* In-place reversal using two pointers */
void reverseString(char *s) {
int n = strlen(s);
int left = 0;
int right = n - 1;
while (left < right) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
A version that reads an entire line (including spaces) — useful if the string can contain spaces:
Variant: read a full line with fgets
#include <stdio.h>
#include <string.h>
void reverseString(char *s) {
int n = strlen(s);
for (int left = 0, right = n - 1; left < right; left++, right--) {
char temp = s[left];
s[left] = s[right];
s[right] = temp;
}
}
int main(void) {
char buffer[200];
printf("Enter a line: ");
if (!fgets(buffer, sizeof(buffer), stdin)) return 1;
/* fgets keeps the trailing newline — strip it if present */
size_t len = strlen(buffer);
if (len > 0 && buffer[len - 1] == '\n') {
buffer[len - 1] = '\0';
}
printf("Original: %s\n", buffer);
reverseString(buffer);
printf("Reversed: %s\n", buffer);
return 0;
}
fgets reads up to a newline or the buffer size, whichever comes first. Unlike scanf("%s"), it preserves spaces. The catch is that it also keeps the trailing newline character in the buffer, so we strip it before reversing. If you don't strip it, the reversed string will start with a newline, which looks weird on screen.
And a version that returns a new reversed copy, leaving the original untouched:
Variant: return a reversed copy
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *reversedCopy(const char *s) {
int n = strlen(s);
char *out = malloc(n + 1);
if (!out) return NULL;
for (int i = 0; i < n; i++) {
out[i] = s[n - 1 - i];
}
out[n] = '\0';
return out;
}
int main(void) {
char buffer[100];
printf("Enter a string: ");
if (scanf("%99s", buffer) != 1) return 1;
char *rev = reversedCopy(buffer);
if (!rev) {
printf("Out of memory.\n");
return 1;
}
printf("Original: %s\n", buffer);
printf("Reversed: %s\n", rev);
free(rev);
return 0;
}
The original buffer is unchanged after this call — reversedCopy allocates a fresh buffer, fills it with the reversed characters, and returns it. The caller is responsible for freeing that buffer. This is the right approach when the input is read-only (e.g., a string literal, or a const char * from elsewhere) and you can't modify it in place.
And a recursive version, which is nice for understanding the algorithm conceptually:
Variant: recursive reversal
#include <stdio.h>
#include <string.h>
void reverseRec(char *s, int left, int right) {
if (left >= right) return;
char temp = s[left];
s[left] = s[right];
s[right] = temp;
reverseRec(s, left + 1, right - 1);
}
int main(void) {
char buffer[100];
printf("Enter a string: ");
if (scanf("%99s", buffer) != 1) return 1;
reverseRec(buffer, 0, (int)strlen(buffer) - 1);
printf("Reversed: %s\n", buffer);
return 0;
}
The recursion is essentially the same two-pointer loop, expressed recursively. The base case left >= right handles both odd-length strings (middle character) and even-length strings (pointers crossing). The recursion depth is O(n/2), which is fine for typical strings — for a 1000-character string, that's 500 stack frames, well within the default stack size.
Program Output
A typical run of the first program:
Enter a string: hello
Original: hello
Reversed: olleh
With a palindrome:
Enter a string: racecar
Original: racecar
Reversed: racecar
With a single character:
Enter a string: a
Original: a
Reversed: a
With a multi-word line (using the fgets variant):
Enter a line: Hello World
Original: Hello World
Reversed: dlroW olleH
And the copy variant (original is preserved):
Enter a string: programming
Original: programming
Reversed: gnimmargorp
Notice the difference: in the first three runs, the original variable is mutated by the in-place function — after the call, buffer holds the reversed string. In the copy variant, the original buffer still holds the original string, because the function returned a new buffer. Both behaviors are correct for their respective designs; the choice depends on what you want.
Step-by-Step Explanation
Let's walk through the in-place version in detail.
1. Understanding the string layout
Suppose the user enters "hello". The array buffer in main looks like this in memory (each cell is one byte):
index: 0 1 2 3 4 5
value: 'h' 'e' 'l' 'l' 'o' '\0'
The characters are contiguous, and the null terminator marks the end. When we call reverseString(buffer), we're passing the address of buffer[0] — a pointer to the first character. The function receives char *s pointing at the 'h'.
2. Computing the length
int n = strlen(s) counts characters until it reaches the null terminator, returning 5 for "hello". It's equivalent to:
int n = 0;
while (s[n] != '\0') n++;
The library version is optimized and handles edge cases, so always use it if you can. For educational purposes, the manual loop shows what's happening.
3. Setting the pointers
left = 0, right = n - 1. For "hello", that's left = 0, right = 4 — pointing at 'h' and 'o' respectively. The - 1 is essential — the last valid character is at index n - 1, not n (which is the null terminator).
4. The swap loop
Each iteration:
- Check
left < right. If not, the loop ends. - Swap
s[left]ands[right]using a temporarychar. - Increment
leftand decrementrightto move inward.
Trace for "hello":
| Iteration | left | right | String after swap |
|---|---|---|---|
| 1 | 0 | 4 | o e l l h |
| 2 | 1 | 3 | o l l e h |
| 3 | 2 | 2 | o l l e h (loop ends — left = right) |
Two swaps: 'h' with 'o', then 'e' with 'l'. The middle 'l' stays put, which is correct — it's the center character and doesn't need to move. After the loop, the string is fully reversed. The null terminator at index 5 is untouched (still '\0'), so the string remains a valid C string.
5. Why the null terminator is preserved
The loop condition right = n - 1 starts from the last character before the terminator. We never touch s[n] (the terminator), so it stays '\0'. This is critical: if we accidentally swapped with the terminator, the string would appear truncated or have trailing garbage. Our design correctly avoids the terminator by starting right at n-1 and stopping when left >= right.
6. Why left < right and not left <= right
For odd-length strings, left and right eventually both point at the middle character. Swapping a character with itself is a no-op, so it doesn't hurt — but it's wasted work, and it's noise in the code. For even-length strings, left and right cross without ever meeting (e.g., left=2, right=2 becomes left=3, right=1). Either way, the strict inequality is the correct stopping condition.
7. Why this modifies the caller's data
In C, arrays decay to pointers when passed to functions. So reverseString(buffer) passes a pointer to buffer[0], not a copy of the array. Inside the function, s[left] and s[right] access the same memory that the caller's buffer array occupies. When we swap characters in s, we're swapping the characters in buffer. When the function returns, buffer holds the reversed string. This is the same pass-by-pointer trick we used for swap(int*, int*) in assignment 9, just applied to a character array.
8. Why string literals can't be reversed
If you call reverseString("hello") (with a literal), the compiler might store "hello" in read-only memory. Attempting to modify it (via the swaps in the function) causes a segmentation fault on most systems. Compilers often warn about this ("warning: passing 'const char *' to parameter of type 'char *' discards qualifiers"), but they don't always error. The safe approach: always pass a mutable buffer — a char array that you own, filled with input from scanf or fgets. Never pass a string literal to a function that modifies the string.
9. The two-pointer pattern
This same pattern — one pointer from the start, one from the end, moving inward — shows up in many algorithms: checking palindromes, merging two sorted arrays, finding pairs that sum to a target, and so on. Once you've internalized the pattern with string reversal, you'll recognize it elsewhere. It's one of the most useful algorithmic shapes in C, and it generalizes far beyond strings.
10. Complexity
The loop runs n/2 iterations, each doing constant work — O(n) time. The space usage is O(1) beyond the input (a few pointers and one char variable). The copy version is also O(n) time but O(n) space (for the new buffer). So the in-place version is strictly more efficient — same time, less space. The only reason to prefer the copy version is if you need to preserve the original.
🔍 Try this: add a printf inside the loop that shows the string after each swap. Run it with "hello" — you'll see the progression "oello" → "olleo" → "olleh". Then run with an even-length string like "abcd" — the swap sequence is "dbca" → "dcba", and the loop ends without the pointers meeting. Both are correct; the loop condition handles both cases uniformly.
Frequently Asked Questions
1. Why doesn't the function return the reversed string?
Because it reverses in place — the caller's buffer is modified directly. A void return type makes that clear: the function's purpose is the side effect (modifying the array), not computing a value. If you want a returned string, use the char *reversedCopy version instead. Both are valid; the in-place version is more efficient (no allocation), the copy version is more flexible (original preserved).
2. What happens if I pass a string literal?
Undefined behavior — often a segmentation fault. String literals in C are typically stored in read-only memory, and attempting to modify them (which reverseString does) causes a crash. Compilers often warn about this when they can detect it (e.g., warning: passing 'const char *' to parameter of type 'char *' discards qualifiers), but the warning isn't guaranteed. The safe rule: only pass mutable buffers to functions that modify their arguments.
3. Why is strlen O(n)?
Because C strings don't store their length — strlen has to walk through the string until it finds the null terminator. For a string of length n, that's n comparisons. There's no shortcut, because the length isn't recorded anywhere. Languages that store length explicitly (like C++ std::string or Go strings) can return it in O(1), but C's zero-terminated strings require O(n) traversal. For the reversal algorithm, this means the total work is O(n) for strlen plus O(n) for the swapping — still O(n) overall, which is optimal.
4. What's the difference between reverseString and the standard strrev?
C doesn't have a standard strrev — it's not in <string.h>. Some compilers provide it as a non-standard extension (_strrev on MSVC, or strrev on some BSD systems), but it's not portable. Writing your own is the portable way to reverse a string. Our implementation matches what strrev does: in-place reversal with a void return type (or returning char * that points to the same buffer, for chaining).
5. Can I reverse a string without modifying it?
Yes — that's the reversedCopy version. It allocates a new buffer, fills it with the reversed characters, and returns it. The original is untouched. This is the version to use when the input is const char * (a function may not modify it) or a string literal. The downside is that the caller must free the returned buffer to avoid memory leaks. For a first pass at this problem, the in-place version is usually the intended exercise; the copy version is the "production-safe" variant when you can't modify the input.
6. What about reversing multi-byte characters or Unicode?
Our function operates on bytes, so it works correctly for ASCII strings (and other single-byte encodings) but not for multi-byte encodings like UTF-8, where a single "character" can be 2–4 bytes. Reversing a UTF-8 string byte-by-byte would corrupt the encoding. For proper Unicode string reversal, you'd need a library (like ICU) or hand-written code that understands the encoding. For most teaching purposes, ASCII is assumed, and byte reversal is correct. If you're working with Unicode, this is a known limitation of byte-level string handling in C.
💡 Tip: Once this works, try writing reverseWords(char *s) — it reverses the order of words, not characters. For example, "hello world foo" becomes "foo world hello". The trick: reverse the whole string first (getting "oof dlrow olleh"), then reverse each word individually. That's a classic interview question, and it uses the same in-place reversal you just wrote — you've already built the tool, now you just need to combine it in a clever way.