String reverse using pointers

后端 未结 2 1553
梦谈多话
梦谈多话 2021-01-25 13:17

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?

         


        
相关标签:
2条回答
  • 2021-01-25 14:04

    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);
    }
    
    0 讨论(0)
  • 2021-01-25 14:04
    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;
    }
    
    0 讨论(0)
提交回复
热议问题