Reputation: 1113
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?
Upvotes: 0
Views: 89
Reputation: 61510
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.
Upvotes: 1
Reputation: 3462
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
}
Upvotes: 3