Reverse a String in C

Reversing a string in C means rearranging its characters from the last character to the first. For example, reversing reverse produces esrever. Common approaches include swapping characters in place, copying characters into another array, using pointers, and using recursion.

Important: strrev() is available in some C libraries, but it is not part of the ISO C standard. Portable C programs should implement string reversal using standard language features. Also, gets(), used in some legacy examples below, is unsafe and was removed from the C standard; use fgets() in new programs.

A string that remains unchanged when reversed is called a palindrome. Examples include level and madam.

strrev() Syntax and Portability

On implementations that provide strrev(), its commonly used syntax is:

</>
Copy
 char *strrev(char *string);

The function modifies the supplied writable character array and usually returns a pointer to it. Because the function is non-standard, code that depends on it may fail to compile with GCC, Clang, or another conforming compiler whose library does not provide it.

Methods to Reverse a String in C

The following examples demonstrate several ways to reverse a null-terminated C string:

  1. Reverse String using strrev() function
  2. Reverse String in place (swapping characters)
  3. Reverse String using recursion
  4. Reverse String using pointers
  5. Reverse a string portably using fgets() and a loop

Example 1 – Reverse String using strrev()

This legacy example calls strrev() to reverse the character array directly. It works only when the compiler and C library provide that function.

C Program

</>
Copy
#include <stdio.h>
#include <string.h>

int main() {
	char str[100];
	printf("Enter a string \n");
	gets(str);
	strrev(str);
	printf("Reverse of the string is %s\n", str);
	return 0;
}

This example is retained to explain existing code, but it should not be copied into a new program because it uses both the non-standard strrev() function and the unsafe gets() function.

Example 2 – Reverse String In-place

In-place reversal swaps the first character with the last character, the second with the second-last, and so on until the two positions meet. It does not require another character array proportional to the input length.

For a string containing n characters, this method performs approximately n/2 swaps. Its time complexity is O(n), and its auxiliary space complexity is O(1).

C Program

</>
Copy
#include<stdio.h>
#include<string.h>
int main()
{
	char str[100],temp;
	int i=0,j=0;
	printf("enter string \n");
	gets(str);
	j=strlen(str)-1;
	while(i<j)
	{
		temp=str[j];
		str[j]=str[i];
		str[i]=temp;
		i++;
		j--;
	}
	printf("\n Reversed string is : ");
	puts(str);
	return 0;
}

The reversal logic is portable, but input should be read with fgets() rather than gets(). A safe, complete version appears later on this page.

Example 3 – Reverse String using Recursion

A recursive solution moves through the string until it reaches the null character, then stores characters while the recursive calls return. This approach takes O(n) time and O(n) call-stack space. For long strings, an iterative solution is usually preferable because it avoids one stack frame per character.

The following legacy example demonstrates the recursive idea:

C Program

</>
Copy
#include<stdio.h>
char* reverse(char* str);                   // declaring recursive function
void main() {
	int i, j, k;
	char str[100];
	char *rev;
	printf("Enter the string:\t");
	gets(str);
	printf("The original string is:%s \t “,str);
	rev = reverse(str);
	printf("The reversed string is: ");
	puts(rev);
}
char* reverse(char *str) {                       // defining the function
	static int i = 0;
	static char rev[100];
	if(*str)
	{
	reverse(str+1);
	rev[i++] = *str;
	}
	return rev;
}

Output

Enter the string:       abcdefghijklmnopqrstuvwxyz
The original string is: abcdefghijklmnopqrstuvwxyz
The reversed string is: zyxwvutsrqponmlkjihgfedcba

The static output array in this example has a fixed capacity and retains state between calls. A reusable function should instead receive the destination array and its capacity, or perform the reversal in place.

Example 4 – Reverse String using Pointers

A pointer can be used to visit characters in a contiguous character array. One pointer starts at the first character and another starts at the final character before '\0'. The pointed-to characters are swapped while the pointers move toward one another.

The underlying character array must be writable. Attempting to modify a string literal through a pointer results in undefined behavior.

C Program

</>
Copy
#include<stdio.h>
#include<string.h>

void reverse(char*);

int main() {
	char s[100];

	printf("Enter a string\n");
	gets(s);
	reverse(s);
	printf("Reverse of the string is \"%s\".\n", s)  
	return 0;
}

void reverse(char *s) {
	int length, c;
	char *begin, *end, temp;
	length = strlen(s);
	begin  = s;
	end    = s;

	for (c = 0; c < length - 1; c++)
		end++;

	for (c = 0; c < length/2; c++) {        
		temp   = *end;
		*end   = *begin;
		*begin = temp;

		begin++;
		end--;
	}
}

This pointer-based method has O(n) time complexity and O(1) auxiliary space. The displayed legacy program still requires a safe input function and a semicolon after its final printf() statement before it can be used as a conforming program.

Portable C Program to Reverse a String without strrev()

The following program uses only standard C library functions. fgets() limits how many characters are stored, and strcspn() removes the newline when one was read. The program then reverses the string by swapping characters.

</>
Copy
#include <stdio.h>
#include <string.h>

void reverse_string(char str[]) {
    size_t left = 0;
    size_t right = strlen(str);

    if (right == 0) {
        return;
    }

    right--;
    while (left < right) {
        char temp = str[left];
        str[left] = str[right];
        str[right] = temp;
        left++;
        right--;
    }
}

int main(void) {
    char str[100];

    printf("Enter a string: ");
    if (fgets(str, sizeof str, stdin) == NULL) {
        return 1;
    }

    str[strcspn(str, "\n")] = '\0';
    reverse_string(str);

    printf("Reversed string: %s\n", str);
    return 0;
}

Sample output

Enter a string: C programming
Reversed string: gnimmargorp C

How the In-place C String Reversal Works

  1. strlen(str) obtains the number of characters before the terminating null character.
  2. left starts at index 0, while right starts at the last character.
  3. The loop swaps the characters at the two indexes.
  4. left increases and right decreases after each swap.
  5. The loop stops when the indexes meet or cross, leaving '\0' in its original terminating position.

Reverse a C String into a Separate Array

If the original string must remain unchanged, copy its characters into a second array in reverse order. The destination needs enough space for every character and the terminating null character.

</>
Copy
#include <stdio.h>
#include <string.h>

int main(void) {
    char source[] = "string";
    char reversed[sizeof source];
    size_t length = strlen(source);

    for (size_t i = 0; i < length; i++) {
        reversed[i] = source[length - 1 - i];
    }
    reversed[length] = '\0';

    printf("Original: %s\n", source);
    printf("Reversed: %s\n", reversed);
    return 0;
}

This method also takes O(n) time, but it uses O(n) additional space. It is appropriate when callers still need the original character order.

Edge Cases in C String Reversal

  • Empty string: Avoid subtracting one from a zero length before checking it, especially when the length uses the unsigned size_t type.
  • One-character string: No swap is required.
  • Spaces: fgets() can read a line containing spaces, unlike token-based input with scanf("%s", ...).
  • Input longer than the buffer: fgets() stores only the characters that fit. Additional input may remain unread.
  • String literals: Copy a literal into a writable array before reversing it in place.
  • UTF-8 text: These byte-oriented examples are intended for single-byte characters. Reversing raw UTF-8 bytes can corrupt multibyte characters; Unicode-aware reversal requires decoding the text first.

Frequently Asked Questions about Reversing Strings in C

Is strrev() a standard C function?

No. strrev() is supplied by some libraries, but it is not defined by the ISO C standard. Use a loop or a custom reversal function when the program must compile across different C implementations.

How can I reverse a string in C without strrev()?

Set one index at the first character and another at the last character. Swap the two characters, move both indexes toward the middle, and repeat while the first index is smaller than the second.

Can reverse() be used directly on a C string?

Standard C has no general reverse() function for strings. A C string is a null-terminated character array, so it must be reversed with custom logic or a non-standard library function. C++ provides different library facilities, but those do not belong to the C language.

Why should gets() not be used to read a string?

gets() cannot limit the number of characters written to the destination array, so input can overflow the buffer. It was removed from the C standard. Use fgets(array, sizeof array, stdin) instead.

Does reversing a C string also move the null character?

No. Reverse only the characters before '\0'. The null character must remain after the final character so that the result is still a valid C string.

C String Reversal QA Checklist

  • Confirm that portable examples do not depend on the non-standard strrev() function.
  • Verify that new input examples use fgets() with the actual destination-array capacity.
  • Test empty, one-character, even-length, odd-length, and space-containing strings.
  • Check that the terminating '\0' remains at the end of the reversed string.
  • Document whether the function modifies the source array or writes to a separate destination array.
  • Do not describe byte-wise reversal as Unicode-safe unless multibyte characters are decoded correctly.

Summary of C String Reversal Methods

In this C Tutorial, we examined string reversal using character swaps, pointers, recursion, a separate destination array, and the non-standard strrev() function. For portable programs, an iterative in-place function combined with bounded input from fgets() is a practical choice. Use a separate array when the original string must be preserved.