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.

Answer from rampion on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › c language › reverse-string-in-c
Reverse String in C - GeeksforGeeks
In C, strrev() defined inside <string.h> can be used to reverse a string.
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.

Discussions

Reversing a string in C.
To post code here, prefix every line of code with 4 extra spaces, or use a site like gist. More on reddit.com
🌐 r/learnprogramming
30
8
April 12, 2015
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
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 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)
How can pointers be used to reverse a string?
Pointers can directly manipulate memory. Using two pointers, one pointing to the start and the other to the end of the string, characters can be swapped while moving inward.
🌐
wscubetech.com
wscubetech.com › resources › c-programming › programs › reverse-string
How to Reverse a String in C? (6 Programs)
🌐
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.
🌐
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!
🌐
Hero Vired
herovired.com › learning-hub › blogs › reverse-a-string-in-c
C Program to Reverse a String Using for Loop and Recursion
In the C programming language, a given string can be reversed using the strrev function, without strrev, recursion, pointers, or another string, or displaying it in the opposite order.
🌐
GeeksforGeeks
geeksforgeeks.org › c language › strrev-function-in-c
strrev() function in C - GeeksforGeeks
January 10, 2025 - Note: This is a non-standard function that works only with older versions of Microsoft C. Below programs illustrate the strrev() function in C: ... // C program to demonstrate // example of strrev() function #include <stdio.h> #include <string.h> ...
Find elsewhere
🌐
Scaler
scaler.com › home › topics › reverse a string in c
Reverse a String in C - Scaler Topics
May 21, 2024 - In the above program, strrev( ) is called on the given string, and reversed string is obtained. Notice that strrev() is not standard function so it may not work in modern compilers. One can write user defined strrev() function. In the above section, we used an in-built function to reverse the string in C.
🌐
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 - The multiple ways to reverse a string in C include the strevv() function, recursive approach, loops, pointers, stacks, and more. Learn with detailed examples.
🌐
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
🌐
Coderanch
coderanch.com › t › 1010714 › languages › PROGRAMMING-reverse-string-built-functions
C PROGRAMMING Question how to reverse a string in C without using built-in functions (C / C++ forum at Coderanch)
March 8, 2026 - Later on, C++ (with Booch OO design) ... To reverse a string in C without using built-in functions, you can manually swap characters from the start and end of the string, moving towards the center....
🌐
Jim Fisher
jameshfisher.com › 2020 › 01 › 05 › how-to-reverse-a-string-in-c
How to reverse a string in C - Jim Fisher
January 5, 2020 - Implement a function void reverse(char* str) in C or C++ which reverses a null-terminated string.
🌐
EDUCBA
educba.com › home › software development › software development tutorials › c programming tutorial › reverse string in c
Reverse String in C | Different Methods to Reverse String in C Language
June 12, 2023 - We can apply the same logic as mentioned in the definition to reverse a string; we can traverse characters in a string from end to start and append one after one. This way, we will have a new string formed by reverse traversal, and this string will be the reversed string.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
W3Schools
w3schools.in › c-programming › examples › reverse-a-string-in-c
Reverse a String in C - W3schools
It is to be noted that for reversing a string of length n, you only need n/2 iterations. Now, once the swapping of strings is done, you need another looping to display the reversed string, which is done using this in our program: ... So, now the user-defined function body is ready with logic. You have to call the function from within the main().
🌐
Sanfoundry
sanfoundry.com › c-program-reverse-string
Reverse a String in C - Sanfoundry
October 18, 2023 - In Recursive Approach, we swap the character at index i with character at index (n-i-1), where n is the size of the string, until i reaches the middle of the string. Examples: Input string: “hello world” “hello world” will be reversed ...
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › reverse a string in c
Reverse a String in C | Without strrev & With Examples
June 23, 2025 - You’ll also explore common mistakes to avoid while working with strings in C, such as improper null termination or incorrect loop conditions. This guide includes logic breakdowns, manual swapping techniques, and a set of practice MCQs to help you test your understanding. Want to master C programming from basics to advanced logic building? Explore upGrad’s Software Engineering Courses and learn C, data structures, and system-level concepts from top instructors. Reversing a string essentially means swapping the characters at the beginning of the string with those at the end, moving towards the center.
🌐
Brainly
brainly.in › computer science › secondary school
Reverse a string in c - Brainly.in
July 3, 2024 - - The pointer-based approach (`Method 1`) is often preferred for its efficiency and clarity, especially in cases where strings are passed as pointers. - Always ensure that the string is null-terminated (`'\0'`) to avoid issues with accessing out-of-bound memory.
🌐
GeeksforGeeks
geeksforgeeks.org › c language › how-to-reverse-a-string-in-c
How to Reverse a String in C? - GeeksforGeeks
July 23, 2025 - two-pointer approach in which we will use two pointers pointing to the first and last index. In every iteration, swap the characters at these positions and move the pointers toward each other until they meet or cross to get the reversed string.
🌐
Tutorial Gateway
tutorialgateway.org › c-program-to-reverse-a-string
C program to Reverse a String
April 2, 2025 - It is something like a program to reverse a string using the swapping technique. /* using temp variable */ #include <stdio.h> #include <string.h> int main() { char Str[100], temp; int i, j, len; printf("\n Actual : "); gets(Str); len = strlen(Str) - 1; for (i = 0; i < strlen(Str)/2; i++) { temp = Str[i]; Str[i] = Str[len]; Str[len--] = temp; } printf("\n Result = %s", Str); return 0; }
🌐
PrepBytes
prepbytes.com › home › c programming › how to reverse a string in c?
How to Reverse a String in C?
May 5, 2023 - Reversing a string in the C means inverting the characters' positions such that the last character becomes the first and first becomes last.