You have string[begin] = '\0' where it should be output[begin] = '\0' Answer from Prof-Whiskers on reddit.com
🌐
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
🌐
Reddit
reddit.com › r/c_programming › how to reverse a string in c without using strrev?
r/C_Programming on Reddit: How to reverse a string in c without using strrev?
September 9, 2019 -

So I have a task which requires me to manipulate arrays and reverse a string. I have written the code but it doesn't work quite perfectly. The problem is that it reverses the string BUT it also includes weird symbols after the reversed string. I'm pretty new to programming and I have tried to find an answer elsewhere but don't know what to look for exactly. I appreciate any constructive feedback, Thanks!

#include <stdio.h>

int main(){

char string[256];
char output[256];
int begin;int end;
int count = 0;

printf("Input a string\n");
fgets(string, 256, stdin);

while (string[count] != '\0'){
count++;

end = count - 1;
}
for (begin = 0; begin < count; begin++) {
output[begin] = string[end];
end--;
}
string[begin] = '\0';

printf("%s\n", output);
}
Discussions

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
How to reverse a string in C#?
verse a string in C efficiently with this guide. We explain two methods: using a two-pointer technique to swap characters in place, and using a loop to construct the reversed string. Includes code snippets and tips to avoid common pitfalls, so you can handle string reversal in C with confidence. More on designgurus.io
🌐 designgurus.io
1
10
June 25, 2024
Trying to reverse a string

Work through this on pen and paper, and see what happens. Meaning, write down your string, and "step" through the loop. You should be able to spot the problem.

More on reddit.com
🌐 r/C_Programming
24
11
March 6, 2021
C - Reverse A String - Weird sprintf Behavior

With sprintf, snprintf, and so on, you are not allowed to use overlapping buffers for the source and the destination:

sprintf(reverse, "%c%s", *letter, reverse);
        ~~~~~~~                   ~~~~~~~

The destination is the buffer reverse, which you allocated at the top of your function. You are pointing to the same buffer in the 4th argument, which is not allowed. See this Q&A about this topic to get the details:

https://stackoverflow.com/questions/19490134/why-behavior-of-sprintf-and-snprintf-is-different-when-we-use-same-source-and-de

EDIT: By the way, this is what the meaning of the word 'restrict' is, if you see it in a function specification. For sprintf, the formal specification looks like this:

#include <stdio.h>
int sprintf(char * restrict s, const char * restrict format, ...);

The first argument, s, is your destination. It must be a pointer to char (that's OK for your example). The word restrict on that pointer means, basically, that that pointer is not allowed to overlap in memory with any of the other pointers in your argument list. It's a so-called "restricted pointer".

More on reddit.com
🌐 r/learnprogramming
4
1
July 24, 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? (8 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? (8 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? (8 Programs)
Top answer
1 of 16
74

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.

🌐
DigitalOcean
digitalocean.com › community › tutorials › reverse-string-c-plus-plus
How to Reverse a String in C++: A Guide with Code Examples | DigitalOcean
April 21, 2025 - Now let us see how we can perform this reverse operation on C++ strings using various techniques. The built-in reverse function reverse() in C++ directly reverses a string.
🌐
Sanfoundry
sanfoundry.com › c-program-reverse-string
Reverse a String in C - Sanfoundry
October 18, 2023 - In each step we swap both characters, increment the first variable and decrement the second variable until the first is less than the second one. Examples: Input string: “hello world” “hello world” will be reversed to “dlrow olleh” Reversed string: “dlrow olleh”
Find elsewhere
🌐
Linux.org
linux.org › home › forums › general linux forums › general computing
How do I reverse a String in C.....? :<
May 30, 2016 - Print_Reverse_String.c: In function ‘main’: Print_Reverse_String.c:12:4: warning: implicit declaration of function ‘gets’ [-Wimplicit-function-declaration] gets(arr); ^ Print_Reverse_String.c:14:4: warning: implicit declaration of function ‘strrev’ [-Wimplicit-function-declaration] strrev(arr); ^ /tmp/ccirfxGT.o: In function `main': Print_Reverse_String.c:(.text+0x2e): warning: the `gets' function is dangerous and should not be used.
🌐
WsCube Tech
wscubetech.com › resources › c-programming › programs › reverse-string
How to Reverse a String in C? (8 Programs)
October 23, 2025 - Learn How to Reverse a String in C with 8 programs, including loops, recursion, and functions. Easy-to-follow examples for beginners and experts!
🌐
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.
🌐
LeetCode
leetcode.com › problems › reverse-string
Reverse String - LeetCode
The input string is given as an array of characters s. You must do this by modifying the input array in-place [https://en.wikipedia.org/wiki/In-place_algorithm] with O(1) extra memory.
🌐
Quora
quora.com › How-do-you-write-a-C-program-with-a-function-that-reverses-a-string-to-spell-backwards
How to write a C program with a function that reverses a string to spell backwards - Quora
Answer (1 of 3): either pass two strings in one string you will have string inputted by user. and other string will be empty. pass both strings and run the loop in the function till the 0th character from the length of the input string which will ...
🌐
Linus Tech Tips
linustechtips.com › software › programming
C Programming - Simple way to reverse a string - Programming - Linus Tech Tips
January 19, 2016 - Right so I made this little C program that lets a user input a string and then outputs that input to the console. I was wondering how I could reverse the string so that whatever the user enters is printed out backwards. Would a for or while loop or something suffice? I'm not really sure how i'd d...
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › reverse-a-string
Reverse a String – Complete Tutorial - GeeksforGeeks
After each swap, increment the left pointer and decrement the right pointer to move towards the center of the string. This will swap all the characters in the first half with their corresponding character in the second half. ... // C++ program to reverse a string using two pointers #include <iostream> using namespace std; string reverseString(string &s) { int left = 0, right = s.length() - 1; // Swap characters from both ends till we reach // the middle of the string while (left < right) { swap(s[left], s[right]); left++; right--; } return s; } int main() { string s = "abdcfe"; cout << reverseString(s); return 0; }
Published   October 3, 2025
🌐
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.
🌐
TutorialsPoint
tutorialspoint.com › reverse-a-string-in-c-cplusplus
Reverse a string in C/C++
May 21, 2025 - Initial string : "Hello" Swap the characters: 'H' > 'o' > "oellH" 'e' > 'l' > "olleH" ... Following is the basic example of reverse() function to solve the reverse of a string:
🌐
Wyzant
wyzant.com › resources › ask an expert
How do you reverse a string in place in C or C++? | Wyzant Ask An Expert
May 16, 2019 - You can reverse a string in-place by swapping its first character with the last one, second character with the second last one and so on.
🌐
LeetCode
leetcode.com › problems › reverse-words-in-a-string
Reverse Words in a String - LeetCode
Example 1: Input: s = "the sky ... Output: "example good a" Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string. Constraints: * 1...
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › reverse a string in c
Reverse a String in C | Without strrev & With Examples
October 14, 2024 - 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