Reversing a string using two pointers in C

reverse a string in c using pointers
c program to reverse a string using swap
reverse words in a string in c using pointers
c program to reverse a string using dynamic memory allocation
reverse in c
reverse a string in c using for loop
string reverse using recursion
reverse a string without using array in c

I'm trying to reverse a string using pointers sptr1 and sptr2, The len gives the correct length of the entered string but the string is not reversed and str1 is not displaying on my terminal. Please provide some insights

#include<stdio.h>
void main()
{
 char str1[10];
 char temp;

 char *sptr1;
 char *sptr2;
 int len;
 printf("Enter a string:");
 scanf("%s",&str1);
 sptr1=str1;
 sptr2=str1;
 while(*sptr1!='\0')
 {
  sptr1++;
 }
 len=sptr1-str1;
 printf("Length of the string:%d",len);

 while(len!=0)
 {
  temp=*sptr1;
  *sptr1=*sptr2;
  *sptr2=temp;

  sptr1--;
  sptr2++;
  len=len-1;
 }
  printf("%s",str1);
 }

After while(*sptr1!='\0')... sptr points to the null-terminator of the string and then you are switching this null terminator with the first character. E.g. you move the null terminator to index 0. You have to decrement sptr before starting the reverse.

You should also decrement len by 2, otherwise you would iterate over the whole array and switch the already switched characters back.

Some other small mistakes: main should return int, not void. scanf("%s", &str1); should be scanf("%s", str1);, str1 already decays to a pointer. You should add \n in your printf statements to have the output in different lines instead of 1 long line.

#include<stdio.h>
int main()
{
 char str1[10];
 char temp;

 char *sptr1;
 char *sptr2;
 int len;
 printf("Enter a string:\n");
 scanf("%s",str1);
 sptr1=str1;
 sptr2=str1;
 while(*sptr1!='\0')
 {
  sptr1++;
 }
 len=sptr1-str1;
 printf("Length of the string:%d\n",len);
 sptr1--;
 while(len>0)
 {
  temp=*sptr1;
  *sptr1=*sptr2;
  *sptr2=temp;

  sptr1--;
  sptr2++;
  len=len-2;
 }
  printf("%s\n",str1);
 }

See it live: https://ideone.com/WAnQLi

Program to Reverse a String using Pointers, After while(*sptr1!='\0') sptr points to the null-terminator of the string and then you are switching this null terminator with the first character. I'm trying to reverse a string using pointers sptr1 and sptr2, The len gives the correct length of the entered string but the string is not reversed and str1 is not displaying on my terminal.

#include<stdio.h>
#include<string.h>
int main(int argc, const char * argv[])
    {
        char s[]="hello";
        strrev(s);
        puts(s);
        return 0;
    }

try strrev function:

char *strrev(char *str);

Reversing a string using two pointers in C, C Program to Reverse a String using Pointer. Below is a program to reverse a string using pointer: #include <stdio.h> int main() { printf("\n\n\t\tStudytonight - Best  null pointer in c; indirection in pointer; C Program to Concat Two Strings without Using Library Function; To Delete all occurrences of Character from the String; Write a c program for swapping of two string; To delete n Characters from a given position in C; To insert a sub-string in to given main string using C

there is only one mistake @mch's code in

len = len - 2;

because of this, program won’t work for string which length is even number correctly. I write to code because of more readability.

#include <stdio.h>


int main()
{
    char str[10];
    printf("Enter a string:\n");
    scanf("%s", str);
    char *ptr1, *ptr2;
    ptr1 = ptr2 = str;
    size_t len = 0;

    while (*ptr1) {
       ++ptr1, ++len;
    }
    printf("Length of the string:%u\n", len);

    for (int k = 0; k < len / 2; ++k) {
        char temp = *(--ptr1);
        *ptr1 = *ptr2;
        *ptr2++ = temp;

    }

    printf("%s\n", str);


}

Interview Questions: How to reverse a string in C/C++ using two , Input: I am coding string reverse! Output: !esrever gnirts gnidoc ma I. Logic to Reverse a string in C: Store the string into a buffer. Take two pointers  Reversing a string in C programming language can be done using various techniques, but here in this program, we show how to reverse a string using pointers. C Program To Reverse a String Source Code Copy paste the below source code or write your own logic into C compilers and run the program to see the result.

Just an additional answer, be very careful with buffer overflow issues. Also a minor detail, you don't really need a len variable.

Below a commented code showing a way to deal carefully with memory writing.

#include <stdio.h>

// Here a way to use constants both as integer and strings
// See https://stackoverflow.com/questions/5459868
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

// Let's define a max length
#define MAX_STRING_LENGTH 10

void main()
{
  char sptr[MAX_STRING_LENGTH + 1]; 

  char *sptr1=sptr,*sptr2=sptr;
  char swap;

  printf("Enter a string (" STR(MAX_STRING_LENGTH) " at most): ");

  // Here, limit the input to sptr size - 1
  // (let the last index for the null character)
  // Example : "%10s" means "at most 10 characters, additional ones
  //           will be removed."
  scanf("%" STR(MAX_STRING_LENGTH) "s",&sptr);

  // Finding the last character BEFORE the NULL character
  while(*(sptr2+1) != '\0') sptr2++;

  // Swaping
  while (sptr2 > sptr1)
    {
      printf("\t-> swaping %c <-> %c\n", *sptr1, *sptr2);
      swap=*sptr1;
      *sptr1=*sptr2;
      *sptr2=swap;
      sptr1++,sptr2--;
    }

  printf("Result : [%s]\n",sptr);
}

Examples (strings with odd and even length):

user:~$ ./a.out 
Enter a string (10 at most): abc
        -> swaping a <-> c
Result : [cba]
user:~$ ./a.out 
Enter a string (10 at most): abcd
        -> swaping a <-> d
        -> swaping b <-> c
Result : [dcba]
user:~$ ./a.out
Enter a string (10 at most): abcdefghijklmnopqrstuvwxyz
        -> swaping a <-> j
        -> swaping b <-> i
        -> swaping c <-> h
        -> swaping d <-> g
        -> swaping e <-> f
Result : [jihgfedcba]

C Program to Reverse a String using Pointer, Can the size of an array be declared at runtime? null pointer in c · indirection in pointer · C Program to Concat Two Strings without Using Library Function · To  C Program to Reverse a String using Pointer. Below is a program to reverse a string using pointer: #include <stdio.h> int main() { printf(" \t\tStudytonight - Best place to learn "); char str[100]; char rev[100]; char *sptr = str; // sptr stores the base address of the str char *rptr = rev; // rptr stores the base address of the reverse int i = -1; printf(" Enter a string: "); scanf

Reverse a string in C using pointers, C program to reverse a string using strrev, without using strrev, recursion and pointers. A string which using pointers. Now we will invert a string using pointers or without using the library function strrev. end++; for (c = 0; c < length/​2; c++) Reverse a String in C - Reversing a string means the string that will be given by the user to your program in a specific sequence will get entirely reversed when the reverse of a string algorithm gets implemented in that particular input string. In the below-mentioned example, two approaches have been used to reverse a string in C language.

Reverse a string using pointers, This loop won't finish: Hide Copy Code. while(*input!=0) { count++; } You could replace it with: Hide Copy Code. while (*(input + count) != C program to reverse a string that a user inputs. If the string is "hello" then, the output is "olleh." C program to reverse a string using strrev, without using strrev, recursion and pointers. A string which remains the same on reversal is a palindrome.

C program to reverse a string, 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26​. 27. #include Function to reverse a C-string without using pointers arithmetic. If the only purpose is to print the string in reverse order, rather than to change the storage, then you could use: void print_reverse_string(const char *str) { const char *src = str + strlen(str); while (src > str) putchar(*--src); }

Comments
  • What does it produce and what do you really want to have?
  • Sir, i need the string entered that is stored in str1 to be reversed after the while. The output screen is just accepting the string and displaying the length even though the printf for str1 exists
  • Looks like you are reversing the string twice.
  • yes sir , thank you! i will check with various other examples and types
  • Sir , can you please explain why it is len=len-2 ?
  • run this code for "aiaz" , its not showing exact reverse. I think the while should be changed to (len>0)
  • You are right, changed to len>0. You only have to iterate over half of the array. Think about the input abcd: You switch a and d, b and c (here you would be done), but when you iterate over the whole array you switch also b and c, a and d again and you get the original string again.