C Example Code2026-03-201 min read
Reverse a character string in C in-place using two-pointer swapping and without using strrev. Full working code and memory safety explained.
Reversing Strings in Standard C
Unlike some high-level languages, standard ISO C does not provide a standard library function like strrev() in standard <string.h> (it was a non-standard MS-DOS/Windows extension). The standard, portable way to reverse a string is using an in-place two-pointer swap algorithm.
C Code Implementation
c (ISO Standard)#include <stdio.h> #include <string.h> void reverseString(char *str) { if (str == NULL) return; int left = 0; int right = strlen(str) - 1; while (left < right) { /* Swap characters at left and right indices */ char temp = str[left]; str[left] = str[right]; str[right] = temp; left++; right--; } } int main() { char greeting[] = "Hello, C Compiler!"; printf("Original String: \"%s\"\n", greeting); reverseString(greeting); printf("Reversed String: \"%s\"\n", greeting); return 0; }
Sample Output
text (ISO Standard)Original String: "Hello, C Compiler!" Reversed String: "!relipmoC C ,olleH"
Complexity Analysis
- Time Complexity:
O(n)where n is string length (loops $⌊ n/2 ⌋$ times). - Space Complexity:
O(1)in-place character manipulation.
Related Programs
- Test string symmetry in Palindrome Program in C.
- Master pointers and character buffers in Pointers in C.