1

我正在尝试使用指针反转字符串。当我尝试打印反转的字符串而不是获取 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);
}
4

2 回答 2

2

你失去了指向字符串开头的指针,所以当你打印出来时,你不是从第一个字符开始,因为str不再指向第一个字符。只需放入一个占位符变量以保留指向字符串开头的指针。

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);
}
于 2012-04-24T17:04:12.950 回答
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;
}
于 2018-09-03T08:15:20.380 回答