#include <algorithm>
std::reverse(str.begin(), str.end());

This is the simplest way in C++.

Answer from Greg Rogers on Stack Overflow
๐ŸŒ
Hero Vired
herovired.com โ€บ learning-hub โ€บ blogs โ€บ reverse-a-string-in-c
C Program to Reverse a String Using for Loop and Recursion
Master cloud architecture, DevOps practices, and automation to build scalable, resilient systems. ... To reverse a string using recursion in C, you can define a recursive function that takes the string as input and returns the reversed string.
Discussions

Fastest way to reverse a string in C - Stack Overflow
For very large strings, the single most important thing will be if the algorithm is cache friendly or not. Here is a version which is cache friendly. It's not an in-place variant. If modified to in place, it can become even more cache friendly. First, we need a simple reverse function which ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
algorithm - How to reverse a C style string completely - Stack Overflow
I'd like to reverse a C style string (null-terminated) completely, i.e. including the null character. The null character should be the first element in the reversed string. More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to reverse a string in c without using strrev?
You have string[begin] = '\0' where it should be output[begin] = '\0' More on reddit.com
๐ŸŒ r/C_Programming
9
1
September 9, 2019
Reversing a string in C - Stack Overflow
I have developed a reverse-string program. I am wondering if there is a better way to do this, and if my code has any potential problems. I am looking to practice some advanced features of C. char* More on stackoverflow.com
๐ŸŒ stackoverflow.com
People also ask

What does it mean to reverse a string in C?
Reversing a string means rearranging its characters so that the first becomes the last, the second becomes the second-last, and so on. For example, reversing "hello" results in "olleh".
๐ŸŒ
wscubetech.com
wscubetech.com โ€บ resources โ€บ c-programming โ€บ programs โ€บ reverse-string
How to Reverse a String in C? (6 Programs)
How does recursion work for reversing a string?
A recursive function swaps the first and last characters, then calls itself on the remaining substring. This continues until the substring size is 0 or 1, effectively reversing the string.
๐ŸŒ
wscubetech.com
wscubetech.com โ€บ resources โ€บ c-programming โ€บ programs โ€บ reverse-string
How to Reverse a String in C? (6 Programs)
How do I reverse a string in C without using a library function?
You can reverse a string by manually swapping characters using loops (e.g., for or while) or recursion. This eliminates the need for built-in functions like strrev().
๐ŸŒ
wscubetech.com
wscubetech.com โ€บ resources โ€บ c-programming โ€บ programs โ€บ reverse-string
How to Reverse a String in C? (6 Programs)
๐ŸŒ
Code with C
codewithc.com โ€บ code with c โ€บ c tutorials โ€บ c program to reverse a string
C Program To Reverse A String - Code With C
May 13, 2015 - The basic working principle to reverse a string in C programming is to swap the position of array element i.e. exchange of the position in character array. As the last element in string is a null character, the first element of array is swapped ...
๐ŸŒ
Wikitechy
wikitechy.com โ€บ technology โ€บ c-algorithm-reverse-string-using-stack
C Algorithm - Reverse a String using Stack - Wikitechy
December 26, 2017 - 3) One by one pop all characters from stack and put them back to string. Following are C and Python programs that implements above algorithm. ... // C program to reverse a string using stack #include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> // A structure to represent a stack struct Stack { int top; unsigned capacity; char* array; }; // function to create a stack of given capacity.
Find elsewhere
๐ŸŒ
WsCube Tech
wscubetech.com โ€บ resources โ€บ c-programming โ€บ programs โ€บ reverse-string
How to Reverse a String in C? (6 Programs)
April 21, 2026 - Learn How to Reverse a String in C with 6 programs, including loops, recursion, and functions. Easy-to-follow examples for beginners and experts!
๐ŸŒ
Unstop
unstop.com โ€บ home โ€บ blog โ€บ reverse a string in c in 10 different ways (+code examples)
Reverse A String In C In 10 Different Ways (+Code Examples)
September 13, 2024 - In-place reversal algorithms using pointers or indices typically have a time complexity of O(n), where n is the length of the string.
๐ŸŒ
Reddit
reddit.com โ€บ r/c_programming โ€บ how to reverse a string in c without using strrev?
How to reverse a string in c without using strrev? : r/C_Programming
September 9, 2019 - In the end, we explicitly add the end of the character symbol in the string. In the end, we print the reverse string. //Using Recursion In this, we will try to reverse the string using the recursive method. Recursion is a method in which a function gives a call to itself.
๐ŸŒ
TechieFreak
techiefreak.org โ€บ home โ€บ blogs โ€บ string โ€บ reverse a string
Reverse a String in C, C++, Java, Python & JavaScript
April 9, 2026 - Convert the string into a character array (if needed). ... Swap characters at left and right. ... Continue until left < right. ... #include #include void reverseString(char str[]) { int left = 0; int right = strlen(str) - 1; while (left < right) ...
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ reverse a string in c
Reverse a String in C - Scaler Topics
May 21, 2024 - One can write user defined strrev() function. In the above section, we used an in-built function to reverse the string in C. Let us define our function to do the same.
๐ŸŒ
W3Schools
w3schools.in โ€บ c-programming โ€บ examples โ€บ reverse-a-string-in-c
Reverse a String in C - W3schools
Then a user-defined function, revAString() is declared and in its definition, reversing the string using swapping logic is written. First of all, you take g (a counter variable), a variable numb of type integer and a temporary variable (name tmpry) used for swapping and initialize this temporary variable with 0.
๐ŸŒ
Sanfoundry
sanfoundry.com โ€บ c-program-reverse-string
Reverse a String in C - Sanfoundry
October 18, 2023 - Here is a C program to reverse a string using loops, recursion, functions, strrev function, Pointers, 2D Arrays, and both recursive & iterative approaches.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ reverse-string-in-c
Reverse String in C - GeeksforGeeks
The most straightforward method to reverse string is by using two pointers to swap the corresponding characters starting from beginning and the end while moving the indexes towards each other till they meet each other.
Published ย  December 5, 2024
Top answer
1 of 16
75

If you want to practice advanced features of C, how about pointers? We can toss in macros and xor-swap for fun too!

#include <string.h> // for strlen()

// reverse the given null-terminated string in place
void inplace_reverse(char * str)
{
  if (str)
  {
    char * end = str + strlen(str) - 1;

    // swap the values in the two given variables
    // XXX: fails when a and b refer to same memory location
#   define XOR_SWAP(a,b) do\
    {\
      a ^= b;\
      b ^= a;\
      a ^= b;\
    } while (0)

    // walk inwards from both ends of the string, 
    // swapping until we get to the middle
    while (str < end)
    {
      XOR_SWAP(*str, *end);
      str++;
      end--;
    }
#   undef XOR_SWAP
  }
}

A pointer (e.g. char *, read from right-to-left as a pointer to a char) is a data type in C that is used to refer to location in memory of another value. In this case, the location where a char is stored. We can dereference pointers by prefixing them with an *, which gives us the value stored at that location. So the value stored at str is *str.

We can do simple arithmetic with pointers. When we increment (or decrement) a pointer, we simply move it to refer to the next (or previous) memory location for that type of value. Incrementing pointers of different types may move the pointer by a different number of bytes because different values have different byte sizes in C.

Here, we use one pointer to refer to the first unprocessed char of the string (str) and another to refer to the last (end). We swap their values (*str and *end), and move the pointers inwards to the middle of the string. Once str >= end, either they both point to the same char, which means our original string had an odd length (and the middle char doesn't need to be reversed), or we've processed everything.

To do the swapping, I've defined a macro. Macros are text substitution done by the C preprocessor. They are very different from functions, and it's important to know the difference. When you call a function, the function operates on a copy of the values you give it. When you call a macro, it simply does a textual substitution - so the arguments you give it are used directly.

Since I only used the XOR_SWAP macro once, it was probably overkill to define it, but it made more clear what I was doing. After the C preprocessor expands the macro, the while loop looks like this:

    while (str < end)
    {
      do { *str ^= *end; *end ^= *str; *str ^= *end; } while (0);
      str++;
      end--;
    }

Note that the macro arguments show up once for each time they're used in the macro definition. This can be very useful - but can also break your code if used incorrectly. For example, if I had compressed the increment/decrement instructions and the macro call into a single line, like

      XOR_SWAP(*str++, *end--);

Then this would expand to

      do { *str++ ^= *end--; *end-- ^= *str++; *str++ ^= *end--; } while (0);

Which has triple the increment/decrement operations, and doesn't actually do the swap it's supposed to do.

While we're on the subject, you should know what xor (^) means. It's a basic arithmetic operation - like addition, subtraction, multiplication, division, except it's not usually taught in elementary school. It combines two integers bit by bit - like addition, but we don't care about the carry-overs. 1^1 = 0, 1^0 = 1, 0^1 = 1, 0^0 = 0.

A well known trick is to use xor to swap two values. This works because of three basic properties of xor: x ^ 0 = x, x ^ x = 0 and x ^ y = y ^ x for all values x and y. So say we have two variables a and b that are initially storing two values va and vb.

  // initially:
  // a == va
  // b == vb
  a ^= b;
  // now: a == va ^ vb
  b ^= a;
  // now: b == vb ^ (va ^ vb)
  //        == va ^ (vb ^ vb)
  //        == va ^ 0
  //        == va
  a ^= b;
  // now: a == (va ^ vb) ^ va
  //        == (va ^ va) ^ vb
  //        == 0 ^ vb
  //        == vb

So the values are swapped. This does have one bug - when a and b are the same variable:

  // initially:
  // a == va
  a ^= a;
  // now: a == va ^ va
  //        == 0
  a ^= a;
  // now: a == 0 ^ 0
  //        == 0
  a ^= a;
  // now: a == 0 ^ 0
  //        == 0

Since we str < end, this never happens in the above code, so we're okay.

While we're concerned about correctness we should check our edge cases. The if (str) line should make sure we weren't given a NULL pointer for string. What about the empty string ""? Well strlen("") == 0, so we'll initialize end as str - 1, which means that the while (str < end) condition is never true, so we don't do anything. Which is correct.

There's a bunch of C to explore. Have fun with it!

Update: mmw brings up a good point, which is you do have to be slightly careful how you invoke this, as it does operate in-place.

 char stack_string[] = "This string is copied onto the stack.";
 inplace_reverse(stack_string);

This works fine, since stack_string is an array, whose contents are initialized to the given string constant. However

 char * string_literal = "This string is part of the executable.";
 inplace_reverse(string_literal);

Will cause your code to flame and die at runtime. That's because string_literal merely points to the string that is stored as part of your executable - which is normally memory that you are not allowed to edit by the OS. In a happier world, your compiler would know this, and cough an error when you tried to compile, telling you that string_literal needs to be of type char const * since you can't modify the contents. However, this is not the world my compiler lives in.

There are some hacks you could try to make sure that some memory is on the stack or in the heap (and is therefore editable), but they're not necessarily portable, and it could be pretty ugly. However, I'm more than happy to throw responsibility for this to the function invoker. I've told them that this function does in place memory manipulation, it's their responsibility to give me an argument that allows that.

2 of 16
28

Just a rearrangement, and safety check. I also removed your non-used return type. I think this is a safe and clean as it gets:

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

void reverse_string(char *str)
{
    /* skip null */
    if (str == 0)
    {
        return;
    }

    /* skip empty string */
    if (*str == 0)
    {
        return;
    }

    /* get range */
    char *start = str;
    char *end = start + strlen(str) - 1; /* -1 for \0 */
    char temp;

    /* reverse */
    while (end > start)
    {
        /* swap */
        temp = *start;
        *start = *end;
        *end = temp;

        /* move */
        ++start;
        --end;
    }
}


int main(void)
{
    char s1[] = "Reverse me!";
    char s2[] = "abc";
    char s3[] = "ab";
    char s4[] = "a";
    char s5[] = "";

    reverse_string(0);

    reverse_string(s1);
    reverse_string(s2);
    reverse_string(s3);
    reverse_string(s4);
    reverse_string(s5);

    printf("%s\n", s1);
    printf("%s\n", s2);
    printf("%s\n", s3);
    printf("%s\n", s4);
    printf("%s\n", s5);

    return 0;
}

Edited so that end will not point to a possibly bad memory location when strlen is 0.

๐ŸŒ
Simplilearn
simplilearn.com โ€บ home โ€บ resources โ€บ software development โ€บ c program to reverse a string using different methods
Program to Reverse a String in C Using Different Methods
September 11, 2025 - Learn C program to reverse a string using two different principles and reasoning without utilizing any preset functions with example code. Start learning now!
Address ย  5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
Top answer
1 of 8
43

Implementation:

As of now, the code is not practical, because the limit is 500 chars including zero termination. It does unnecessary copying. You need to determine the actual length of the string by relying on the fact that C strings are null terminated.

size_t length = 0;
while (*(str + length) != 0)
{
    ++length;
}

Notice that I'm using size_t, because it is meant to be used to describe size of the objects in memory. Despite it is easy to do it manually, you should always use strlen when possible:

size_t length = strlen(str);

It should be noted that the function returns the length without null terminator. Then we allocate memory for result, since we are creating new string, rather than making changes in place:

char* result = malloc(length + 1);
if (result == NULL)
{
    return NULL;
}

We check for succession of allocation, as was suggested in the comments. If allocation failed, further operations will definitely invoke undefined behavior, so we return NULL. length + 1 is for null terminator. Then, we immediately null terminate it:

result[length] = 0;

Now we need to capture the position of the last character in the original string, to start copying from there. It is right before null terminator, which is on index length, so needed position is length - 1. There is an edge case of length 0, so we should check for that first

if (length == 0)
{
    return result;
}
size_t last = length - 1;

Then we write algorithm that writes contents of the first string into the second in reverse order:

size_t it = 0;
while (it <= last)
{
    result[it] = str[last - it];
    ++it;
}

then simply return the result:

return result;

Although the implementation has good performance, there are some opportunities to make micro optimizations. The function input type should be const char*, since we don't modify original string. Additionally, it should be noted that the caller is responsible for freeing up malloc'd memory.

Cosmetics:

Name of the function is a little hard to read, so I'd suggest str_reverse. Also, c is not good name at all, so it would be better if it's name str

Put together:

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

char* str_reverse(const char* str)
{
    size_t length = strlen(str);

    char* result = malloc(length + 1);
    if (result == NULL)
    {
        return NULL;
    }

    result[length] = 0;

    if (length == 0)
    {
        return result;
    }

    size_t last = length - 1;
    size_t it = 0;
    while (it <= last)
    {
        result[it] = str[last - it];
        ++it;
    }

    return result;
}

int main(void) {
    const char* str = "ABCD";
    char* reversed = str_reverse(str);

    printf("%s\n", reversed);
    if (str[4] != 0)
    {
        printf("problems\n");
    }

    free(reversed);
    return 0;
}
2 of 8
26

Returning a pointer to a local variable

Returning a pointer to the local variable output is incorrect. It may happen to work but it is wrong to do so, because the storage for that local variable goes out of scope the moment you return from the function. To be correct, you should either malloc a buffer and return it (preferred) or make output be static.

Empty initializer list

Initializing output to {} is nonstandard C and should be avoided. The standard way to initialize an array to zeroes is {0}.

Unnecessary variable

Your input variable is unnecessary because you can just use c wherever you used input.

Bad algorithm

Your string reversal function takes \$O(n^2)\$ time when it should only take \$O(n)\$ time. The problem is that you use strcat to append one character at a time, and strcat needs to find the end of the string each time. If you ever find yourself using strcat in a loop, it's probably not the best way.

Other things

  • Using scanf("%s",in); to read into a fixed size string is unsafe and could result in a buffer overflow.
  • You should also print a newline when you print the result otherwise your shell prompt will be on the same line as your output.
  • Your function argument c could be marked const since you do not modify it. Also, c sounds like a character not a string.
  • Since you are already using C99 style variable declarations, you can put the int i declaration inside the for loop.

Suggested rewrite

char *reverseString(const char *str)
{
    size_t len = strlen(str);
    char  *ret = calloc(len+1, sizeof(char));

    if (ret == NULL)
        return NULL;

    for (size_t i = 0, j = len-1; i < len; i++, j--)
        ret[i] = str[j];
    return ret;
}
๐ŸŒ
Upgrad
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ reverse a string in c
Reverse a String in C | Without strrev & With Examples
June 23, 2025 - Understand the different ways to reverse a string in C, including the strrev() function, library function, recursion function, pointers, and more with this tutorial. C Program to Reverse a String Using Different Ways
๐ŸŒ
Rosetta Code
rosettacode.org โ€บ wiki โ€บ Reverse_a_string
Reverse a string - Rosetta Code
March 28, 2026 - For maximum compatibility, this program uses only the basic instruction set (S/360) and an ASSIST macro (XPRNT) to keep the code as short as possible. * Reverse a string 21/05/2016 REVERSE CSECT USING REVERSE,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) prolog ST R13,4(R15) " ST R15,8(R13) " LR R13,R15 " MVC TMP(L'C),C tmp=c LA R8,C @c[1] LA R9,TMP+L'C-1 @tmp[n-1] LA R6,1 i=1 LA R7,L'C n=length(c) LOOPI CR R6,R7 do i=1 to n BH ELOOPI leave i MVC 0(1,R8),0(R9) substr(c,i,1)=substr(tmp,n-i+1,1) LA R8,1(R8) @c=@c+1 BCTR R9,0 @tmp=@tmp-1 LA R6,1(R6) i=i+1 B LOOPI next i ELOOPI XPRNT C,L'C print c L R13,4(0,R13) epilog LM R14,R12,12(R13) " XR R15,R15 " BR R14 exit C DC CL12'edoC attesoR' TMP DS CL12 REGEQU END REVERSE