简体   繁体   中英

Reversing a string using pointers

I am currently studying different algorithms to practice my coding strengths and came across an alogrithm to reverse a string. It uses pointers and I am alittle confused on what is going on. The code is below:

void reverse(char *str) {
   char * end = str;
   char tmp;
   if (str) {
      while (*end) {
         ++end;
      }
  --end;
  while (str < end) {
     tmp = *str;
     *str++ = *end;
     *end-- = tmp;
  }
 }
}

So in this code, the end is put to the end of the strings memory location in the first while loop. Then the second while is where I am getting confused. I do not understand what is going with the *str++ = *end and *end-- = *temp.

Why is this happening like this? When the line tmp = *str occurs, does the first letter of the string go into temp or am I thinking of this incorrectly?

As you already know end points to the last character. Now in the second for loop he is just swapping the first character with the last character and then moving the str pointer towards its rights and end to its left.

while (str < end) {
     tmp = *str;  // storing the char at str in temp
     *str++ = *end;  // storing the char at end at str position and then incrementing str .. i.e. moving str right
     *end-- = tmp;  // storing the char in tmp at end position and then decrementing tmp .. i.e. moving tmp left 
  }

It is always best to try an example, below is what the second while loop would look like for the word "hello" . The value of *str is always stored in tmp , then *end is copied into *str , the overall effect is that after each iteration the values of *str and *end switch. Both the post-increment on *str and the post-decrement on *end do not take effect until after the assignment statements.

    *end
    v
hello        tmp='h'
^
*str
------------------
   *end
   v
oellh        tmp='e'
 ^
 *str
------------------
  *end
  v
olleh        tmp='e'
  ^
  *str

execution stops here because str < end produces a false value since they now both point to the same character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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