简体   繁体   English

使用指针反向字符串

[英]String reverse using pointers

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? 我正在尝试使用指针反转字符串。当我尝试打印反转的字符串而不是获取DCBA时,我仅以BA身份退出?有人可以帮我吗?

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

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. 您将失去指向字符串开头的指针,因此,在打印输出时,您不是从第一个字符开始,因为str不再指向第一个字符。 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);
}
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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM