String reverse using pointers

和自甴很熟 提交于 2019-12-04 05:21:45

问题


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);
}

回答1:


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);
}



回答2:


char* strrev(chr* src)
{      
       char* dest
       int len=0, index=0 , rindex=0;

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

       rindex=len-1;

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

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


return dest;
}


来源:https://stackoverflow.com/questions/10302524/string-reverse-using-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!