1

I'm trying to reverse a string using pointers.When i try to print the reversed string instead of getting DCBA i'm getting out only as BA?Can anyone help me on this?

#include<stdio.h>
void reverse(char *);
void main()
{
  char str[5] = "ABCD";
  reverse(str);
}

void reverse(char *str)
{
  char *rev_str = str;
  char temp;
  while(*str)
      str++;
  --str;

  while(rev_str < str)
  {
      temp = *rev_str;
      *rev_str = *str;
      *str = temp;   
      rev_str++;      
      str--;
  }
  printf("reversed string is %s",str);
}
2

2 Answers 2

2

You're losing your pointer to the beginning of the string, so when you print it out you're not starting from the first character, because str no longer points to the first character. Just put in a placeholder variable to keep a pointer to the beginning of the string.

void reverse(char *str)
{
  char *begin = str; /* Keeps a pointer to the beginning of str */
  char *rev_str = str;
  char temp;
  while(*str)
      str++;
  --str;

  while(rev_str < str)
  {
      temp = *rev_str;
      *rev_str = *str;
      *str = temp;   
      rev_str++;      
      str--;
  }
  printf("reversed string is %s\n", begin);
}
Sign up to request clarification or add additional context in comments.

Comments

0
char* strrev(chr* src)
{      
       char* dest
       int len=0 ;    //calculate length of the src string
       int index=0 ;  // index for dest (output) string
       int rindex=0; //Index to be counted from end toward beginning of src string

       //Calculate length of the string
       //Keep iterating till it reaches to null char '\0'

       while(*(src+len) != '\0')
       { len++ }

       //pointing rindex at the last character of src string 
       rindex=len-1;

       
       //Start copying from last char of src string at first index of dest array
       // Copying second last char of src string at second index of dest array and so on ..


       while(rindex > =0)
       {
           *(dest+index) = *(src + rindex)
            index++;
            rindex--;
       }

   // Finally covert array of char into string , by inserting a null char at the end of dest array

      *(dest+index) = '\0';


return dest;
}

1 Comment

While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.